注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if (root1 == null || root2 == null) return false;
boolean res = isSameOrMore(root1, root2);
if (!res) {
res = isSameOrMore(root1.left, root2);
}
if (!res) {
res = isSameOrMore(root1.right, root2);
}
return res;
}
public boolean isSameOrMore(TreeNode root1, TreeNode root2) {
// root2子树已经遍历完了,true
if (root2 == null) return true;
// root1母树已经遍历完了但root2子树没有遍历完,false
if (root1 == null) return false;
if (root1.val != root2.val) return false;
return isSameOrMore(root1.left, root2.left) && isSameOrMore(root1.right, root2.right);
}
}