题解 | #重建二叉树#

重建二叉树

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

记录下菜鸡写的比较详细的写法

public class JZ4_重建二叉树 {
    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre.length == 0 || in.length == 0) return null;
        //前序数组的第一个值即接下来的树的头节点
        TreeNode root = new TreeNode(pre[0]);

        //找到前序的根在中序的位置
        int rootPos = -1;
        for (int i = 0; i < in.length; i++) {
            if (in[i] == pre[0]) {
                rootPos = i;
                break;
            }
        }
        //构建下一次递归的数组
        int[] nextPreLeft = Arrays.copyOfRange(pre, 1, rootPos + 1);
        int[] nextInLeft = Arrays.copyOfRange(in, 0, rootPos);
        int[] nextPreRight = Arrays.copyOfRange(pre, rootPos + 1, pre.length);
        int[] nextInRight = Arrays.copyOfRange(in, rootPos + 1, pre.length);

        root.left = reConstructBinaryTree(nextPreLeft, nextInLeft);
        root.right = reConstructBinaryTree(nextPreRight, nextInRight);

        return root;
    }
}
全部评论

相关推荐

牛至超人:您好,京东物流岗了解一下吗?负责精加工食品的端到端传输
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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