题解 | #树的子结构#

树的子结构

https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88

/**
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;

        boolean flag1 = res(root1,root2);

        boolean flag2 = HasSubtree(root1.left,root2);

        boolean flag3 = HasSubtree(root1.right,root2);
        
        return flag1 || flag2 || flag3;
    }

    public boolean res(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 != null) return false;

        if (root1 == null || root2 == null) return true;

        if (root1.val != root2.val) return false;

        return res(root1.left, root2.left) && res(root1.right, root2.right);
    }
}

两个递归

1.HasSubtree遍历所有节点

2.res判断当前节点与子树是否一致

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务