26、树的子结构

1、题目描述:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

2、思路:

 

 

 

3、代码:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    //第一步判断,遍历树 A ,找到和树 B 根节点值相同的节点
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result=false;
        if(root2!=null&&root1!=null){
            if(root1.val==root2.val){
                result=doseTree1HaveTree2(root1,root2);
            }
            if(!result){
                result=HasSubtree(root1.left,root2);
            }
            if(!result){
                result=HasSubtree(root1.right,root2);
            }
        }
        return result;
    }
    //第二步判断,判断 A,B 树的左子节点、右子节点是否还相同
    public boolean doseTree1HaveTree2(TreeNode nood1,TreeNode nood2){
        if(nood2==null){
            return true;
        }
        if(nood1==null){
            return false;
        }
        if(nood1.val!=nood2.val){
            return false;
        }
        return doseTree1HaveTree2(nood1.left,nood2.left)&& doseTree1HaveTree2(nood1.right,nood2.right);
    }
}
上一篇:【leetcode】1305. All Elements in Two Binary Search Trees


下一篇:1305. All Elements in Two Binary Search Trees