leetcode算法基础 第七天 深搜/广搜

117. 填充每个节点的下一个右侧节点指针 II

题目
这道题,比较简单的思想就是层次遍历,每次遍历一层的节点,每层的节点数由n记录,不能直接i < queue.size()因为队列是在不停变化的。

public Node connect(Node root) {
    if (root == null) return null;
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()){
        Node last = null;
        int n = queue.size();
        for (int i = 0; i < n; i++){
            Node f = queue.poll();;
            if (f.left != null){
                queue.add(f.left);
            }
            if (f.right != null){
                queue.add(f.right);
            }
            if (i > 0){
                last.next = f;
            }
            last = f;
        }
    }
    return root;
}

还可以根据上一层已经建立好连接的思想,加入全局变量,nextStart记录下一层开始的父节点,last记录当前层最后一位,关键是for循环遍历当前层所有节点

Node last = null, nextStart = null;

public Node connect1(Node root) {
    if (root == null) {
        return null;
    }
    Node start = root;
    while (start != null) {
        last = null;
        nextStart = null;
        for (Node p = start; p != null; p = p.next) {
            if (p.left != null) {
                handle(p.left);
            }
            if (p.right != null) {
                handle(p.right);
            }
        }
        start = nextStart;
    }
    return root;
}

public void handle(Node p) {
    if (last != null) {
        last.next = p;
    }
    if (nextStart == null) {
        nextStart = p;
    }
    last = p;
}

572. 另一棵树的子树

题目
该题还有kmp算法和哈希树两种解法,需要继续完善。

public boolean isSubtree(Node s, Node t) {
    if (t == null) return true;   // t 为 null 一定都是 true
    if (s == null) return false;  // 这里 t 一定不为 null, 只要 s 为 null,肯定是 false
    return isSubtree(s.left, t) || isSubtree(s.right, t) || isSameTree(s,t); // 判断是左子树、右子树还是当前树和目标树相同
}

//前序遍历查找节点
public Node findRoot(Node root, Node subRoot){
    if (root == null) return null;
    if (root.val == subRoot.val) return root;
    Node re = null;
    re = findRoot(root.left, subRoot);
    if (re != null) return re;
    re = findRoot(root.right, subRoot);
    return re;
}

//判断两个树是否相同
public boolean isSameTree(Node s, Node t){
    if (s == null && t == null) return true;
    if (s == null || t == null) return false;
    if (s.val != t.val) return false;
    return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值