输入两棵二叉树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) {
//先查找根节点一样的节点
boolean result = false;
if (root1 != null && root2 != null) {
if (root1.val == root2.val) {
result = judgeOthers(root1,root2);
}
if (!result) { //左子树
result = HasSubtree(root1.left,root2);
}
if (!result) { //右子树
result = HasSubtree(root1.right,root2);
}
}
return result;
}
public boolean judgeOthers(TreeNode root1,TreeNode root2) {
if (root2 == null) { //子树所有节点判断完成,且未出现与A树不一致的节点
return true;
}
if (root1 == null) { //B树节点比A树节点多,肯定不是其子树
return false;
}
if (root1.val != root2.val) { //再判断过程中,只要有一个节点的值不一致,就结束此次判断
return false;
}
return judgeOthers(root1.left,root2.left) && judgeOthers(root1.right,root2.right);
}
}