题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
AC代码
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//如果是空树,返回false
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if(root1==null||root2==null)
return false;
if(isPart(root1,root2))
return true;
return HasSubtree(root1.left,root2)||HasSubtree(root1.right,root2);
}
public boolean isPart(TreeNode r1,TreeNode r2){
if(r2==null)
return true;
if(r1==null||(r1.val!=r2.val))
return false;
return isPart(r1.left,r2.left)&&isPart(r1.right,r2.right);
}
}
来源:CSDN
作者:NayelyAA
链接:https://blog.csdn.net/weixin_40992982/article/details/104101016