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 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.length==0 || postorder.length==0) return null; 13 14 TreeNode root = new TreeNode(postorder[postorder.length-1]); 15 int i; 16 for(i=0; i<inorder.length; i++){ //找到根节点在中序序列中的位置 17 if(inorder[i] == postorder[postorder.length-1]) break; 18 } 19 int[] left, right, npostorder; 20 if(i>0){ 21 left = new int[i]; //左子树中的节点 22 System.arraycopy(inorder, 0, left, 0, left.length); 23 }else left = new int[0]; 24 if(inorder.length - i -1 > 0){ //右子树中的节点 25 right = new int[inorder.length - i -1]; 26 System.arraycopy(inorder, i+1, right, 0, right.length); 27 }else right = new int[0]; 28 29 npostorder = new int[postorder.length - 1];//删除根节点 30 System.arraycopy(postorder, 0, npostorder, 0, npostorder.length); 31 root.right = buildTree(right, npostorder); //构建右子树 32 npostorder = new int[postorder.length - right.length - 1];//删除右子树中节点 33 System.arraycopy(postorder, 0, npostorder, 0, npostorder.length); 34 root.left = buildTree(left, npostorder);//构建左子树 35 return root; 36 } 37 }