题目描述:
和上面一道题目类似,这里因为我在主函数传入的是length-1,导致调bug半天,无奈
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(null == inorder || inorder.length == 0){
return null;
}
// 找到根节点
int rootnum = postorder[postorder.length - 1];
int i = 0;
for (; i < inorder.length; i++) {
if(inorder[i] == rootnum){
break;
}
}
TreeNode root = new TreeNode(rootnum);
// 找到左子树的节点
System.out.println("start" + i);
root.left = getleft(inorder, postorder,0, i, i - 1);
// 右子树的节点下标
root.right = getleft(inorder, postorder, i + 1, postorder.length, postorder.length - 2);
return root;
}
public TreeNode getleft(int []inorder,int[] postorder,int start,int end,int rootnum){
if(start >= end){
return null;
}
TreeNode root = new TreeNode(postorder[rootnum]);
int i = start;
for (; i < end; i++) {
if(inorder[i] == postorder[rootnum]){
break;
}
}
// 找到左子树的节点
root.left = getleft(inorder, postorder,start, i ,rootnum - end + i);
// 右子树的节点下标
root.right = getleft(inorder, postorder, i + 1, end, rootnum - 1);
return root;
}
}