Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Solution:
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { ATreeNode root = Buildtreerecur (preorder,inorder,0,preorder.length-1,0,inorder.length-1); - returnRoot; - } the - PublicTreeNode Buildtreerecur (int[] Preorder,int[] inorder,intPreS,intPreE,intInsintInE) { - if(Pres>pree)return NULL; - if(pres==PreE) { +TreeNode leaf =NewTreeNode (Preorder[pres]); - returnLeaf; + } A at intRootval =Preorder[pres]; - intindex =InS; - for(inti=ins;i<=ine;i++) - if(inorder[i]==rootval) { -index =i; - Break; in } - to intLeftlen = index-InS; + intRightlen = InE-index; - theTreeNode 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 =NewTreeNode (rootval);Panax NotoginsengRoot.left =Leftchild; -root.right=Rightchild; the returnRoot; + } A the}
Construct Binary Tree from preorder and inorder traversal
Leetcode-construct Binary Tree from inorder and preorder travesal