Written by myself:
Idea:
start with the node, and the value of the root node of the stock is equal, then compare the values of the left subtree and the right subtree to make the B tree equal, until the value of the B neutron tree is false. If it can be found from the root node, then return true
otherwise find from the left subtree.
Otherwise, find it from the right subtree.
/**
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;
}
以这个根节点为为起点判断是否包含Tree2
if(root1.val == root2.val){
if(hasEqueal(root1, root2)){
return true;
}
}
boolean ret = false;
//如果找不到,那么就再去root的左儿子当作起点,去判断时候包含Tree2
if(HasSubtree(root1.left,root2)){
return true;
}
//如果还找不到,那么就再去root的右儿子当作起点,去判断时候包含Tree2
if(HasSubtree(root1.right,root2)){
return true;
}
return false;
}
public boolean hasEqueal(TreeNode root1,TreeNode root2){
//如果Tree2还没有遍历完,Tree1却遍历完了。返回false
if(root1 == null){
return false;
}
//如果Tree2还没有遍历完,Tree1却遍历完了。返回false
if(root2 == null){
return true;
}
if(root1.val == root2.val){
boolean leftEqual = false;
boolean rightEqual = false;
if(root2.left == null){
leftEqual = true;
} else {
leftEqual = hasEqueal(root1.left, root2.left);
}
if(root2.right == null){
rightEqual =true;
} else {
rightEqual = hasEqueal(root1.right, root2.right);
}
return leftEqual&&rightEqual;
}
return false;
}
}
Other writing reference:
public class Solution {
public static boolean HasSubtree(TreeNode root1, TreeNode root2) {
boolean result = false;
//当Tree1和Tree2都不为零的时候,才进行比较。否则直接返回false
if (root2 != null && root1 != null) {
//如果找到了对应Tree2的根节点的点
if(root1.val == root2.val){
//以这个根节点为为起点判断是否包含Tree2
result = doesTree1HaveTree2(root1,root2);
}
//如果找不到,那么就再去root的左儿子当作起点,去判断时候包含Tree2
if (!result) {
result = HasSubtree(root1.left,root2);
}
//如果还找不到,那么就再去root的右儿子当作起点,去判断时候包含Tree2
if (!result) {
result = HasSubtree(root1.right,root2);
}
}
//返回结果
return result;
}
public static boolean doesTree1HaveTree2(TreeNode node1, TreeNode node2) {
//如果Tree2已经遍历完了都能对应的上,返回true
if (node2 == null) {
return true;
}
//如果Tree2还没有遍历完,Tree1却遍历完了。返回false
if (node1 == null) {
return false;
}
//如果其中有一个点没有对应上,返回false
if (node1.val != node2.val) {
return false;
}
//如果根节点对应的上,那么就分别去子节点里面匹配
return doesTree1HaveTree2(node1.left,node2.left) && doesTree1HaveTree2(node1.right,node2.right);
}
}