题目描述
输入两棵二叉树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) {
if(null == root2 || null == root1){
return false;
}
return sub(root1, root2, root2);
}
public boolean sub(TreeNode root1, TreeNode root2, TreeNode tmp){
if(null == root2){
return true;
}
if(null == root1){
return false;
}
if(root1.val == root2.val
&& sub(root1.left, root2.left, tmp) && sub(root1.right, root2.right, tmp)){
return true;
}
return sub(root1.left, tmp, tmp) || sub(root1.right, tmp, tmp);
}
}