Construct Binary Tree
105. Construct Binary Tree from Preorder and Inorder Traversal
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0) return null;
int num = preorder[0];
int len = 0;
for(int i=0; i<inorder.length; i++){
if(inorder[i] == num)
len = i;
}
TreeNode node = new TreeNode(num);
node.left = buildTree(Arrays.copyOfRange(preorder, 1, 1+len),
Arrays.copyOfRange(inorder, 0, len));
node.right = buildTree(Arrays.copyOfRange(preorder, 1+len, preorder.length),
Arrays.copyOfRange(inorder, 1+len, inorder.length));
return node;
}106. Construct Binary Tree from Inorder and Postorder Traversal
889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals.
Example
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7]
find the length of left tree and use it split the left tree and right tree
Preorder and postorder left tree length are the same, and pre[1] the head of left tree, use is to find the last position in postorder
Last updated
Was this helpful?