Given inorder and postorder traversal of a tree, construct the binary tree.
Notice
You may assume that duplicates do not exist in the tree.
Given inorder [1,2,3]
and postorder [1,3,2]
, return a tree:
2
/ \
1 3
1 /** 2 * Definition for a binary tree node. 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 if (inorder == null || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null; 13 return buildTree(inorder, 0, postorder, 0, inorder.length); 14 } 15 16 public TreeNode buildTree(int[] inorder, int inStart, int[] postorder, int postStart, int length) { 17 if (length == 0) return null; 18 TreeNode root = new TreeNode(postorder[postStart + length - 1]); 19 int index = findIndex(inorder, root.val); 20 root.left = buildTree(inorder, inStart, postorder, postStart, index - inStart); 21 root.right = buildTree(inorder, index + 1, postorder, postStart + (index - inStart), length - (index - inStart) - 1); 22 return root; 23 } 25 public int findIndex(int[] inorder, int val) { 26 for (int i = 0; i < inorder.length; i++) { 27 if (inorder[i] == val) { 28 return i; 29 } 30 } 31 return -1; 32 } 33 }