Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the
tree.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode buildTree(int[] inorder, int[] postorder) { 12 int length = inorder.length; 13 return buildTreeHelp(inorder, postorder, 0, length - 1, 0, length - 1); 14 } 15 public TreeNode buildTreeHelp(int[] inorder, int[] postorder, int startI, int endI, int startP, int endP){ 16 TreeNode root = null; 17 if(startI <= endI){ 18 root = new TreeNode(postorder[endP]); 19 int rootPosition = startI; 20 int newendP = startP; 21 for(int i = startI; i <= endI; ++i){ 22 if(inorder[i] == postorder[endP]){ 23 rootPosition = i; 24 break; 25 } 26 else 27 ++newendP; 28 } 29 root.left = buildTreeHelp(inorder, postorder, startI, rootPosition - 1, startP, newendP - 1); 30 root.right = buildTreeHelp(inorder, postorder, rootPosition + 1, endI, newendP, endP - 1); 31 } 32 return root; 33 } 34 }
leetcode---Construct Binary Tree from Inorder and Postorder Traversal