Description Title
input two binary A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree of any sub-structure).
Idea, two steps,
1 to find the root node of the same node B in A, referred to as A1 tree
2. Analyzing A1 contains B,
public class Main13 {
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public boolean subtree(TreeNode root1,TreeNode root2){
if (root1==null&&root2==null)//如果root2为空,说明B已经匹配完了,返回真
return true;
else if (root1!=null&&root2==null)//如果root2为空,说明B已经匹配完了,返回真
return true;
else if (root1==null&&root2!=null)//如果root1先为空,说明B中的节点,A却没有,返回假
return false;
else {//如果都不为空
if (root1.val!=root2.val){//判断值是否相等
return false;
}
return subtree(root1.left,root2.left)&&subtree(root1.right,root2.right);//分别判断左右两边是否也是一样的
}
}
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean flag=false;
if (root1!=null&&root2!=null){
if (root1.val==root2.val){//如果A中当前的节点和B的根节点相同,
flag= subtree(root1,root2);//则判断A的子树是否和B相同
}
if (flag==false){//如果没找到,就看A的左节点是否和B的根节点相同
flag=HasSubtree(root1.left,root2);
}
if(flag==false){//如果还没找到,就看A的右节点是否和B的根节点相同
flag=HasSubtree(root1.right,root2);
}
}
return flag;
}
}