/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean checkSubTree(TreeNode t1, TreeNode t2) {
// 条件过滤
if (t2 == null){
return true;
}
if (t1 == null){
return false;
}
// 判断是否想等
return bfs(t1, t2) || checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2);
}
private boolean bfs(TreeNode t1, TreeNode t2){
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null || t1.val != t2.val) return false;
return bfs(t1.left, t2.left) && bfs(t1.right, t2.right);
}
}
力扣:面试题 04.10. 检查子树
最新推荐文章于 2025-12-11 15:34:25 发布
本文探讨了如何使用二叉树节点实现深度优先搜索(DFS)和广度优先搜索(BFS)算法,以判断两个二叉树是否为子树。重点讲解了`checkSubTree`函数的实现,以及`bfs`辅助函数在解决此类问题中的关键作用。

355

被折叠的 条评论
为什么被折叠?



