🔢
Algorithms & Data
Ctrlk
  • Overview
    • 1. Sort
    • 2. Data Structures
    • 3. How to construct Algorithm? Paradigm
  • Algorithm Problems
    • Problem Sources
    • AlgoExpert
    • Daily Algorithms
  • Top 75 LeetCode Questions to Save Your Time
    • Source
    • Problems
      • Interval
      • Heap
      • Array
      • Binary
      • Graph
      • Tree
        • x 297. Serialize and Deserialize Binary Tree
        • x 105. Construct Binary Tree from Preorder and Inorder Traversal
        • x 212. Word Search II
        • 211. Design Add and Search Words Data Structure
        • 208. Implement Trie (Prefix Tree)
        • 235. Lowest Common Ancestor of a Binary Search Tree
        • 230. Kth Smallest Element in a BST
        • 98. Validate Binary Search Tree
        • 572. Subtree of Another Tree
        • 297. Serialize and Deserialize Binary Tree ?
        • 102. Binary Tree Level Order Traversal
        • 124. Binary Tree Maximum Path Sum
        • 226. Invert Binary Tree
        • 100. Same Tree
        • 104. Maximum Depth of Binary Tree
      • Dynamic Programming
      • String
      • Matrix
      • Linked List
  • Tip
    • Page 2
    • LinkedList
Powered by GitBook
On this page
  1. Top 75 LeetCode Questions to Save Your Time
  2. Problems
  3. Tree

x 105. Construct Binary Tree from Preorder and Inorder Traversal

PreOrder, InOrder, PostOrder

LogoConstruct Binary Tree from Preorder and Inorder Traversal - LeetCodeLeetCode

https://8iggy.tistory.com/112

time: O(n)

space: O(n)

Previousx 297. Serialize and Deserialize Binary TreeNextx 212. Word Search II

Last updated 13 days ago

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */

let preorderIdx = 0;
let inroderMap;
var buildTree = function (preorder, inorder) {
    preorderIdx = 0;
    inorderMap = inorder.reduce((acc, curr, i) => (acc[curr] = i, acc), {});
    return construct(preorder, 0, preorder.length - 1);
};

function construct(preorder, left, right) {
    if (preorderIdx >= preorder.length) {
        return null;
    }

    if (left > right) {
        return null;
    }

    const value = preorder[preorderIdx++];
    const node = new TreeNode(value);

    const inorderIdx = inorderMap[value];

    node.left = construct(preorder, left, inorderIdx - 1);
    node.right = construct(preorder, inorderIdx + 1, right);

    return node;
}