剑指offer-树的子结构

Posted by franki on May 2, 2021

树的子结构

输入两棵二叉树A和B,判断B是不是A的子结构。

思路

1 在树A中找到和树B的根节点的值一样的节点R

2 判断树A中以R为根节点的子树是不是包含和树B一样的结构

代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} A
 * @param {TreeNode} B
 * @return {boolean}
 */
var isSubStructure = function(A, B) {
    let result = false;
    if (A !== null && B !== null) {
        if (A.val === B.val) {
            result = doesHasSubTree(A, B);
        }
        if (!result) {
            result = isSubStructure(A.left, B);
        }
        if (!result) {
            result = isSubStructure(A.right, B);
        }
    }
    return result;
};

function doesHasSubTree(A, B) {
    if (B === null) {
        return true;
    }
    if (A === null) {
        return false;
    }
    if (A.val !== B.val) {
        return false;
    }
    return doesHasSubTree(A.left, B.left) && doesHasSubTree(A.right, B.right);
}

复杂度分析

  • 时间复杂度: O(MN)
  • 空间复杂度: O(M)