输入两棵二叉树A,B,判断B是不是A的子结构。约定空树不是任意一个树的子结构。
public class Solution {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public boolean check(TreeNode root1, TreeNode root2) {
if (root2 == null) {
return true;
}
if (root1 == null || root1.val != root2.val) {
return false;
}
return check(root1.left, root2.left) && check(root1.right, root2.right);
}
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return false;
}
return check(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
}
}
测试用例:root1 = {6,8,7,9,2,#,#,#,#,4,7} , root2 = {8,9,2} 。流程如下:
①判断 if (root1 == null || root2 == null)
②进入到 return check(root1, root2) 进行判断,由于root1.val != root2.val,所以check中返回false
③进入到 HasSubtree( root1.left , root2) 或 HasSubtree( root1.right , root2 ) ,然后①,②,此时root1.val == root2.val == 8 ,return check( root1.left , root2.left ) && check( root1.right , root2.right ); 成功的判别了{8,9,2},之后 root2.left == null , 代入进 check中时,
、、if ( root2 == null)
、、、、return true;
结束,也就是HasSubtree返回true。