Construct Binary Tree from Preorder and Inorder Traversal
cheatsheet1999 opened this issue · 0 comments
cheatsheet1999 commented
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.
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;
};