输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
从A根结点对比,若没有,则从A左子树寻找,若也没有,则从右子树寻找。若找到相等结点,则从该结点开始往下遍历左右结点是否相同,若相同则返回true,否则false。
/**
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 = DosehasSubTree(root1,root2);//若相等则从该结点开始向下遍历左右结点
}
if(!result){
result = HasSubtree(root1.left,root2);//若不等,则从A左子树寻找
}
if(!result){
result = HasSubtree(root1.right,root2);//若左子树也不存在相等,则从A右子树寻找
}
}
return result;
}
public static boolean DosehasSubTree(TreeNode root1,TreeNode root2){//遍历相等的值
if((root1 == null)&&(root2 != null))return false;//若A遍历完而B没遍历完,则返回错误
if((root2 == null))return true;//若B遍历完,则说明都相等,则返回true
if(root1.val != root2.val)return false;//若出现不相等值,则返回false
return DosehasSubTree(root1.left,root2.left)&&DosehasSubTree(root1.right,root2.right);
//从左子树开始一一对应对比
}
}