题解 | #从中序与后序遍历序列构造二叉树#

从中序与后序遍历序列构造二叉树

http://www.nowcoder.com/practice/ab8dde7f01f3440fbbb7993d2411a46b

这个题的思路是和根据中前遍历重建二叉树类似的。因为后续遍历的最后一个元素总是根节点,那么只需要先找到后序遍历中的根节点,再把数组分为左右两个区间就能找到左子树与右子树。

public class Solution {
    public TreeNode buildTree (int[] inorder, int[] postorder) {
        if(postorder.length==0)return null;
        TreeNode root = new TreeNode(postorder[postorder.length-1]);
        for(int i=0;i<inorder.length;++i){
            if(root.val==inorder[i]){
                root.left = buildTree(
                    Arrays.copyOfRange(inorder,0,i),
                    Arrays.copyOfRange(postorder,0,i)
                ); 
                root.right = buildTree(
                    Arrays.copyOfRange(inorder,i+1,inorder.length),
                    Arrays.copyOfRange(postorder,i,inorder.length-1)
                );
                return root;
            }
        }
        return root;
    }
}
全部评论

相关推荐

头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
点赞 评论 收藏
分享
评论
11
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务