Construct Binary Tree from inorder and Postorder traversal
Total Accepted: 31041 submissions: 115870
Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Problem Solving Ideas:
Modify the following code to solve the problem, the Java implementation is as follows:
static public TreeNode Buildtree (int[] inorder, int[] postorder) {return Buildtree (postorder, inorder, 0, Postorder.lengt H-1, 0, inorder.length-1); } static public TreeNode Buildtree (int[] postorder, int[] inorder, int pbegin, int pEnd, int ibegin, int iend) { if (pbegi n>pend) return null; TreeNode root = new TreeNode (Postorder[pend]); int i = Ibegin; for (; i<iend;i++) if (inorder[i]==root.val) break ; int lenleft = I-ibegin; Root.left = Buildtree (Postorder, Inorder, Pbegin, Pbegin+lenleft-1, Ibegin, i-1); Root.right = Buildtree (Postorder, Inorder, Pbegin+lenleft, PEnd-1, i+1, iend); return root; }
Java for Leetcode 106 Construct Binary Tree from inorder and Postorder traversal