Leetcode 剑指Offer26 树的子结构

 

  JAVA:

    public final boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null) return false;
        if (isSame(A, B)) return true;
        return isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }

    private final boolean isSame(TreeNode a, TreeNode b) {
        if (b == null) return true;
        if (a == null || a.val != b.val) return false;
        return isSame(a.left, b.left) && isSame(a.right, b.right);
    }

  JS:

var isSubStructure = function (A, B) {
    if (!A || !B) return false;
    if (isSame(A, B)) return true;
    return isSubStructure(A.left, B) || isSubStructure(A.right, B);
};

var isSame = function (a, b) {
    if (!b) return true;
    if (!a || a.val != b.val) return false;
    return isSame(a.left, b.left) && isSame(a.right, b.right);
}

 

posted @ 2021-03-05 20:28  牛有肉  阅读(53)  评论(0编辑  收藏  举报