重建二叉树

重建二叉树

http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6

    //解题思路:
    //1、用前序确定root节点
    //2、然后在中序中用root节点左右分割,就分辨是左右子树了。
    //3、在左右子树中,用递归重复1、2
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre == null || pre.length == 0 || in ==null || in.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[0]);
        for(int i = 0; i<in.length; i++) {
            if(pre[0] == in[i]) {
                root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i));
                root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1 , pre.length), Arrays.copyOfRange(in, i+1, in.length));
            }
        }
        return root;
    }
全部评论

相关推荐

06-20 19:40
中原工学院 Java
网络存储:十几天不会让你拉人办卡就结束了吧?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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