|
| 1 | +/** |
| 2 | + * Given inorder and postorder traversal of a tree, construct the binary tree. |
| 3 | + * |
| 4 | + * Note: |
| 5 | + * You may assume that duplicates do not exist in the tree. |
| 6 | + * |
| 7 | + * For example, given |
| 8 | + * |
| 9 | + * inorder = [9,3,15,20,7] |
| 10 | + * postorder = [9,15,7,20,3] |
| 11 | + * Return the following binary tree: |
| 12 | + * |
| 13 | + * 3 |
| 14 | + * / \ |
| 15 | + * 9 20 |
| 16 | + * / \ |
| 17 | + * 15 7 |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * Definition for a binary tree node. |
| 22 | + * public class TreeNode { |
| 23 | + * int val; |
| 24 | + * TreeNode left; |
| 25 | + * TreeNode right; |
| 26 | + * TreeNode(int x) { val = x; } |
| 27 | + * } |
| 28 | + */ |
| 29 | + |
| 30 | +public class ConstructBinaryTreeFromInorderAndPostorderTraversal106 { |
| 31 | + public TreeNode buildTree(int[] inorder, int[] postorder) { |
| 32 | + if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0 || inorder.length != postorder.length) return null; |
| 33 | + int len = inorder.length; |
| 34 | + return buildTree(inorder, 0, len-1, postorder, 0, len-1); |
| 35 | + } |
| 36 | + |
| 37 | + private TreeNode buildTree(int[] inorder, int ii, int ij, int[] postorder, int pi, int pj) { |
| 38 | + if (ii > ij) return null; |
| 39 | + int midVal = postorder[pj]; |
| 40 | + TreeNode curr = new TreeNode(midVal); |
| 41 | + if (pi == pj) return curr; |
| 42 | + |
| 43 | + int mid = ii; |
| 44 | + while (inorder[mid] != midVal) mid++; |
| 45 | + |
| 46 | + curr.left = buildTree(inorder, ii, mid-1, postorder, pi, pi+(mid-1-ii)); |
| 47 | + curr.right = buildTree(inorder, mid+1, ij, postorder, pi+(mid-ii), pj-1); |
| 48 | + return curr; |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments