Topic:
Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { intlen=preorder.length; if(len==0) return NULL; TreeNode Root=NewTreeNode (preorder[0]); if(len==1) returnRoot; intIndex=0; for(inti=0;i<inorder.length;i++){ if(inorder[i]==preorder[0]) {index=i; Break; } } if(index>0){ int[]preleft=New int[index]; int[]inleft=New int[index]; System.arraycopy (Preorder,1,preleft,0, index); System.arraycopy (Inorder,0,inleft,0, index); Root.left=Buildtree (Preleft,inleft); } if(len-index-1>0){ int[]preright=New int[Len-index-1]; System.arraycopy (Preorder,index+1,preright,0,len-index-1); int[]inright=New int[Len-index-1]; System.arraycopy (Inorder,index+1,inright,0,len-index-1); Root.right=Buildtree (preright,inright); } returnRoot; }}
[Leetcode] Construct Binary Tree from preorder and inorder traversal