572. Subtree of Another Tree

本文提供了一种高效的算法来解决LeetCode上的一道题:检查一棵树是否是另一棵树的子树。该算法通过递归方式比较两棵树的结构和节点值,实现速度快且内存使用效率高。

题目描述

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
在这里插入图片描述在这里插入图片描述

题目链接

https://leetcode.com/problems/subtree-of-another-tree/

方法思路

public class Solution {
    //Runtime: 10 ms, faster than 94.11% 
    //Memory Usage: 41.5 MB, less than 82.09%
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (s == null) return false;
        if (isSame(s, t)) return true;
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }
    
    private boolean isSame(TreeNode s, TreeNode t) {
        if (s == null && t == null) return true;
        if (s == null || t == null) return false;
        if (s.val != t.val) return false;
        return isSame(s.left, t.left) && isSame(s.right, t.right);
    }
}

错误的思路:(我不知道错在哪了,可能是想的太复杂了吧)

class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(t == null) return true;
        if(s == null && t != null) return false;
        TreeNode node = find(s, t.val);
        List<Integer> ls = inorder(s);
        List<Integer> lt = inorder(t);
        if(ls.size() != lt.size()) return false;
        for(int i = 0; i < ls.size(); i++){
            if(ls.get(i) != lt.get(i))
                return false;
        }
        return true;
    }
    public List<Integer> inorder(TreeNode root){
        List<Integer> ans = new LinkedList<>();
        if(root == null) return ans;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            ans.add(cur.val);
            cur = cur.right;
        }
        return ans;
    }
    public TreeNode find(TreeNode root ,int val){
        if(root == null) return root;
        if(root.val == val) return root;
        TreeNode left = find(root.left, val);
        TreeNode right = find(root.right, val);
        if(left != null) return left;
        if(right != null) return right;
        return null;
    }
}
这是一个非常关键且常见的疑问! 你提出的问题是: > **“为什么只要 `B == null` 就返回 `true`?此时如果 `A` 不为空,不是就错误了吗?”** 这个问题涉及到我们对“子结构”定义的理解。 --- ## ✅ 明确概念:什么是“子结构”? 在本题中(LeetCode 剑指 Offer 26. 树的子结构),题目明确规定: > 若存在与 B 具有相同结构和节点值的子树,就说树 A 是包含树 B 的一个子结构。 **特别注意:空树不算是子结构。也就是说,当 B 是空树时,不能认为它是任何树的子结构。** 所以: - 当 `B == null` 时,无论 `A` 是否为 `null`,都应返回 `false` - 只有当 `B != null` 并且它的结构完全出现在 `A` 中某一部分时,才返回 `true` --- ## 📌 回到你的问题: ### ❓代码中出现如下逻辑: ```java if (B == null) { return true; } ``` 这个逻辑其实是在判断:“当前这一层是否满足匹配”,它适用于一种不同的场景 —— **判断一棵树是否是另一棵树的子树(subtree)**,而不是“子结构(substructure)”。 --- ## 🔁 对比两个概念 | 类型 | 定义 | 空树是否是子结构 | |--------------|------|------------------| | 子结构(substructure) | 必须结构和值完全一致,且不能是空结构 | ❌ 不允许 | | 子树(subtree) | 结构一致即可,可以是空树 | ✅ 允许 | --- ## ✅ 正确写法(适用于本题) 既然题目要求的是“子结构”,我们就应该这样写: ```java private boolean match(TreeNode A, TreeNode B) { // 如果 B 为空,说明已经成功匹配完 if (B == null) { return false; // ❌ 不允许空结构作为子结构 } // 如果 B 不为空,而 A 为空,则失败 if (A == null) { return false; } // 值不相等也失败 if (A.val != B.val) { return false; } // 继续递归左右子树 return match(A.left, B.left) && match(A.right, B.right); } ``` --- ## ✅ 所以你应该这样理解: - `if (B == null)` 返回 `true`:这是用于“子树”判断(如 LeetCode 100. Same Tree / 572. Subtree of Another Tree) - `if (B == null)` 返回 `false`:这是用于“子结构”判断(如本题) --- ## ✅ 示例验证 测试用例: ```java A = [1,2,3,4] B = [3] ``` 其中: - `A` 的右孩子是 `3`,`B` 是单个节点 `3` - 匹配过程: - `match(3, 3)` 成功 - `match(null, null)` → 按照上面逻辑返回 `false` - 所以整体返回 `true` ✅ 这才是正确的处理方式。 --- ## ✅ 总结 | 判断类型 | B 为空时返回值 | 题目示例 | |----------|----------------|-----------| | 子结构(substructure) | `false` | 剑指 Offer 26 | | 子树(subtree) | `true` | LeetCode 572 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值