/**
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 result = false;
if(root1.val == root2.val)
{
result = Tree1EqualsTree2(root1,root2); / /根节点相同时,比较root1,root2子节点的值
}
if(!result){
result = HasSubtree(root1.left,root2);//此根节点的值不相同,则root1要向下一层左子节点查询
}
if(!result){
result = HasSubtree(root1.right,root2);//左子节点也不同,则root1要查询右子节点
}
return result;
}
public boolean Tree1EqualsTree2(TreeNode node1,TreeNode node2){
if(node2== null) // node2为空,如果node1也为空则完全一样,若node1不为空,那么node2就可能是node1根节点的一个分支
{
return true;
}
if(node1== null){// node1为空,node2不为空,不相同
return false;
}
if(node1.val != node2.val)
{
return false;
}
return Tree1EqualsTree2(node1.left,node2.left) && Tree1EqualsTree2(node1.right,node2.right);
//根节点的值相同,比较左右子节点的值是否相同
}
}
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 result = false;
if(root1.val == root2.val)
{
result = Tree1EqualsTree2(root1,root2); / /根节点相同时,比较root1,root2子节点的值
}
if(!result){
result = HasSubtree(root1.left,root2);//此根节点的值不相同,则root1要向下一层左子节点查询
}
if(!result){
result = HasSubtree(root1.right,root2);//左子节点也不同,则root1要查询右子节点
}
return result;
}
public boolean Tree1EqualsTree2(TreeNode node1,TreeNode node2){
if(node2== null) // node2为空,如果node1也为空则完全一样,若node1不为空,那么node2就可能是node1根节点的一个分支
{
return true;
}
if(node1== null){// node1为空,node2不为空,不相同
return false;
}
if(node1.val != node2.val)
{
return false;
}
return Tree1EqualsTree2(node1.left,node2.left) && Tree1EqualsTree2(node1.right,node2.right);
//根节点的值相同,比较左右子节点的值是否相同
}
}