105. Construct Binary Tree from Preorder and Inorder Traversal Sequences
Given two integer arrays preorder
and inorder
, where is the preorder traversalpreorder
of a binary tree and is the inorder traversal of the same tree , construct a binary tree and return its root node.inorder
Example 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
Example 2:
输入: preorder = [-1], inorder = [-1]
输出: [-1]
hint:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
andinorder
have no repeating elementsinorder
Both appear inpreorder
preorder
Guaranteed to be the preorder traversal sequence of the binary treeinorder
Guaranteed to be the inorder traversal sequence of a binary tree
problem solving ideas
recursion
- Find the root node (that is,
preorder
the first number of the array) - According to the root node, distinguish the left and right subtrees (that is, find
inorder
the subscript of the array corresponding to the root node val)- Left subtree child node: all the numbers before
inorder
the corresponding subscript . - Right subtree child node: all numbers after
inorder
the corresponding subscript .
- Left subtree child node: all the numbers before
- Collect the array of child nodes and traverse each to form a binary tree.
Code
var buildTree = function(preorder, inorder) {
if(preorder.length===0) return null;
let rootNode=preorder[0];
let leftLength=inorder.indexOf(rootNode);
let root=new TreeNode(rootNode);
root.left=buildTree(preorder.slice(1,leftLength+1),inorder.slice(0,leftLength));
root.right=buildTree(preorder.slice(leftLength+1),inorder.slice(leftLength+1));
return root;
};