Skip to content

Construct Binary Tree from Preorder and Inorder Traversal #8

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
cheatsheet1999 opened this issue Sep 5, 2021 · 0 comments
Open

Comments

@cheatsheet1999
Copy link
Owner

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Screen Shot 2021-09-04 at 8 54 05 PM


This is a very basic question and tested us about inorder and preorder traverse.

/**
 * 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}
 */
var buildTree = function(preorder, inorder) {
    if(!inorder.length) return null;
   // The first node of preorder is always the root of the tree
    let root = new TreeNode(preorder.shift())
    let index = inorder.indexOf(root.val);
   // Inorder traverse, every elements on the left side of the root would be the left tree,
   // the elements on the right of the root will be the right subtree
    let leftTree = inorder.slice(0, index);
    let rightTree = inorder.slice(index + 1);
    
    root.left = buildTree(preorder, leftTree);
    root.right = buildTree(preorder, rightTree);
    return root;
};
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant