Leetcode-Construct Binary Tree from inorder and preorder travesal

时间:2021-09-28 19:27:13

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Solution:

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode root = buildTreeRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
return root;
} public TreeNode buildTreeRecur(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE){
if (preS>preE) return null;
if (preS==preE){
TreeNode leaf = new TreeNode(preorder[preS]);
return leaf;
} int rootVal = preorder[preS];
int index = inS;
for (int i=inS;i<=inE;i++)
if (inorder[i]==rootVal){
index = i;
break;
} int leftLen = index-inS;
int rightLen = inE - index; TreeNode leftChild = buildTreeRecur(preorder,inorder,preS+1,preS+leftLen,inS,index-1);
TreeNode rightChild = buildTreeRecur(preorder,inorder,preE-rightLen+1,preE,index+1,inE);
TreeNode root = new TreeNode(rootVal);
root.left = leftChild;
root.right= rightChild;
return root;
} }

Construct Binary Tree from Preorder and Inorder Traversal