解题思路:
递归
后序遍历的最后一个结点是根结点。根据这个根节点可以在中序遍历中找到左子树和右子树的结点集合,然后递归找到左子树和右子树的根节点。
提交代码:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length==0) return null;
if(inorder.length==1) {
TreeNode node=new TreeNode(inorder[0]);
return node;
}
TreeNode root=new TreeNode(postorder[postorder.length-1]);
int p=0,size=inorder.length;
while(inorder[p]!=root.val)
p++;
int[] leftInOrder=new int[p];
int[] leftPostOrder=new int[p];
for(int i=0;i<p;i++) {
leftInOrder[i]=inorder[i];
leftPostOrder[i]=postorder[i];
}
root.left=buildTree(leftInOrder,leftPostOrder);
int[] rightInOrder=new int[size-p-1];
int[] rightPostOrder=new int[size-p-1];
for(int i=p+1,j=0;i<size;i++,j++)
rightInOrder[j]=inorder[i];
for(int i=p,j=0;i<size-1;i++,j++)
rightPostOrder[j]=postorder[i];
root.right=buildTree(rightInOrder,rightPostOrder);
return root;
}
}
运行结果:

本文介绍了一种使用递归方法构建二叉树的算法,该算法基于后序遍历和中序遍历序列,通过查找根节点并在中序序列中确定左右子树的范围,递归地构建出完整的二叉树。
680

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



