同上一题,这一题是由inorder和postorder来确定树,对于postorder,root要从尾部开始找
另外,在从一个order到另外一个order时,要用相对距离来计算!即从第一个order算出dist是多少,然后应用这个dist到第二个order上
package Level4;
import Utility.TreeNode;
/**
* Construct Binary Tree from Inorder and Postorder Traversal
*
* Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
*
*/
public class S141 {
public static void main(String[] args) {
int[] inorder = {1,2,3};
int[] postorder = {3,2,1};
TreeNode root = buildTree(inorder, postorder);
root.print();
}
public static TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0){
return null;
}
return rec(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
}
public static TreeNode rec(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd){
if(postEnd < 0 || postEnd>=postorder.length){
return null;
}
TreeNode root = new TreeNode(postorder[postEnd]);
int rootIndex; // rootIndex in inorder[]
for(rootIndex=0; rootIndex inStart){ // 锁定范围,否则会Memory out of limit!
root.left = rec(inorder, postorder, inStart, rootIndex-1, postStart, postStart+leftSubTreeLen-1);
}
if(rootIndex < inEnd){
root.right = rec(inorder, postorder, rootIndex+1, inEnd, postStart+leftSubTreeLen, postEnd-1);
}
return root;
}
}
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return rec(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
}
public TreeNode rec(int[] inorder, int[] postorder, int inorderLeft, int inorderRight, int postorderLeft, int postorderRight) {
if(inorderLeft > inorderRight || postorderLeft > postorderRight) {
return null;
}
int root = postorder[postorderRight];
TreeNode rootNode = new TreeNode(root);
int inorderRootPos = inorderLeft;
for(inorderRootPos=inorderLeft; inorderRootPos<=inorderRight; inorderRootPos++) {
if(inorder[inorderRootPos] == root) {
break;
}
}
int dist = inorderRootPos - inorderLeft;
rootNode.left = rec(inorder, postorder, inorderLeft, inorderRootPos-1, postorderLeft, postorderLeft+dist-1);
rootNode.right = rec(inorder, postorder, inorderRootPos+1, inorderRight, postorderLeft+dist, postorderRight-1);
return rootNode;
}
}