Given inorder and postorder traversal of a tree, construct the binary tree.
与问题非常类似,唯一区别在于这一次确定root的位置由post traversal来确定,为最后一个元素。
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 if (inorder.length==0 || postorder.length==0 || inorder.length!=postorder.length) {13 return null;14 }15 int len = inorder.length;16 HashMapmap = new HashMap ();17 for (int i=0; i map) {24 if (posL>posR || inL>inR) {25 return null;26 }27 TreeNode root = new TreeNode(postorder[posR]);28 int index = map.get(postorder[posR]);29 root.left = helper(postorder, posL, posL+index-1-inL, inorder, inL, index-1, map);30 root.right = helper(postorder, posL+index-inL, posR-1, inorder, index+1, inR, map);31 return root;32 }33 }