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

题目链接:https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

 

解释:

二叉树A                 二叉树B

这里的的二叉树B就是就算是二叉树A的一个子结构,但是二叉树B并不是二叉树A的子树。关于判断二叉树另一个子树的题目见我另一博客https://blog.csdn.net/qq_34115899/article/details/80228332

它们在代码的写法上只有细微差别。

本题AC:

/**
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;
        if (isSameSubStructure(root1, root2))    return true; // 结构对等的比较
        return HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2); // 子树中查找对等结构
    }
    private boolean isSameSubStructure(TreeNode root1,TreeNode root2) {
        if (root2 == null)    return true; // B的子结点为空就不用判断了
        if (root1 == null)    return false;
        return root1.val == root2.val && isSameSubStructure(root1.left, root2.left)
            && isSameSubStructure(root1.right, root2.right);
    }
}

 

=======================Talk is cheap, show me the code========================