Leetcode572:判断另一棵树的子树
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210216231319627.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzA0NTI4,size_16,color_FFFFFF,t_70)
解题思路
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210216231351302.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzA0NTI4,size_16,color_FFFFFF,t_70)
判断二叉树是否相等
代码示例
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
return Find(s, t);
}
public static boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val==q.val&&isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public static boolean Find(TreeNode root, TreeNode t) {
if(root==null){
return false;
}
if(root.val==t.val){
if(isSameTree(root, t)){
return true;
}
}
if(Find(root.left, t)){
return true;
}
return Find(root.right, t);
}
}