Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* 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) {
if(inorder.length<=0 && postorder.length<=0) return null;
return buildCore(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
public TreeNode buildCore(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
int rootVal=postorder[postEnd];
TreeNode node=new TreeNode(rootVal);
if(postEnd==postBegin){
return node;
}
int inRoot=inBegin;
while(inorder[inRoot]!=rootVal && inRoot!=inEnd) inRoot++;
if(inRoot==inEnd && inorder[inRoot]!=rootVal) return null;
int lenLeft=inRoot-inBegin;
if(lenLeft>0){
node.left=buildCore(inorder,inBegin,inRoot-1,postorder,postBegin,postBegin+lenLeft-1);
}
if(inRoot<inEnd){
node.right=buildCore(inorder,inRoot+1,inEnd,postorder,postBegin+lenLeft,postEnd-1);
}
return node;
}
}
254

被折叠的 条评论
为什么被折叠?



