题解 | #重建二叉树#

重建二叉树

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

 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        return doReConstructBinaryTree(pre, vin, 0, pre.length - 1);
    }
    
    int l = 0;

    public TreeNode doReConstructBinaryTree(int[] pre, int[] vin, int p, int q) {
        if (pre.length == 0) {
            return null;
        }
        int h = pre[l]; // 从头到位开始记录pre数组,表示每次的头节点
        TreeNode node = new TreeNode(h);
        // 找到vin数组中pre[l]的下标。左边是node节点的左子树,右边是node节点的右子树。
        int i = -1;
        for (int n : vin) {
            i++;
            if (n == pre[l]) {
                break;
            }
        }
        l++;
        if (p == q) { // 左右范围之内剩下一个节点, 直接返回。
            return node;
        }
        if (i > p && i <= q) { // 左子树存在条件。
            node.left = doReConstructBinaryTree(pre, vin, p, i - 1);
        }
        if (i >= p && i < q) { // 右子树存在条件
            node.right = doReConstructBinaryTree(pre, vin, i + 1, q);
        }
        return node;
    }
}
全部评论

相关推荐

02-05 08:49
已编辑
武汉大学 Web前端
野猪不是猪🐗:36k和36k之间亦有差距,ms的36k和pdd的36k不是一个概念
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务