Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Subscribe to see which companies asked this question
Hide TagsTree Array Depth-first SearchHide Similar Problems(M) Construct Binary Tree from preorder and inorder traversal
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] inorder,int[] postorder) {HashMap<integer, integer> Inorderindex =NewHashmap<integer, integer>(inorder.length); for(inti = 0; i< inorder.length; ++i) {inorderindex.put (inorder[i], i); } returnBuildtree (inorder, 0, Inorder.length, postorder, 0, Postorder.length, Inorderindex); } PrivateTreeNode Buildtree (int[] inorder,intInorderfrom,intInorderto,int[] Postorder,intPostorderfrom,intPostordeto, Hashmap<integer, integer>Inorderindex) { if(Inorderfrom>=inorderto | | postorderfrom>=Postordeto)return NULL; intRootvalue = postorder[postordeto-1]; TreeNode Root=NewTreeNode (Rootvalue); intRootindex =Inorderindex.get (Rootvalue); Root.left=Buildtree (inorder, Inorderfrom, Rootindex, Postorder, Postorderfrom, Postorderfrom + (Rootindex-inorderfrom), inorderindex); Root.right= Buildtree (Inorder, rootindex+1, Inorderto, Postorder, Postorderfrom+ (Rootindex-inorderfrom), postordeTo-1, Inorderindex); returnRoot; }}
106. Construct Binary Tree from inorder and Postorder traversal