题解 | #重建二叉树#

重建二叉树

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;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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