Construct Binary Tree from inorder and Postorder traversal
Problem:
Given Inorder and Postorder traversal of a tree, construct the binary tree.
Ideas:
Dfs
My Code:
Public classSolution { PublicTreeNode Buildtree (int[] inorder,int[] postorder) { if(Inorder = =NULL|| Inorder.length = = 0)return NULL; if(Inorder.length = = 1)return NewTreeNode (inorder[0]); intLen =postorder.length; inttarget = postorder[len-1]; intindex =GetIndex (inorder, target); TreeNode Root=NewTreeNode (target); Root.left= Buildtree (Arrays.copyofrange (Inorder,0,index), Arrays.copyofrange (postorder,0, index)); Root.right= Buildtree (Arrays.copyofrange (inorder, index+1, Len), Arrays.copyofrange (Postorder, index, len-1)); returnRoot; } Public intGetIndex (int[] inorder,inttarget) { for(inti = 0; i < inorder.length; i++) { if(Inorder[i] = =target)returni; } return-1; }}View Code
Construct Binary Tree from inorder and Postorder traversal