leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

面试题26. 树的子结构

Open fireairforce opened this issue 5 years ago • 0 comments

单纯的递归下去就行了:

/**
 * 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) {
    if(!A || !B) {
        return false;
    }
    var hasSubTree = function(A,B) {
        if(!B) {
           return true;
        } 
        if(!A) {
            return false;
        }
        if(A.val !== B.val) {
            return false;
        }
        return hasSubTree(A.left,B.left) && hasSubTree(A.right,B.right);
    }
    return hasSubTree(A,B) || isSubStructure(A.left,B) || isSubStructure(A.right,B);
};

fireairforce avatar Feb 21 '20 15:02 fireairforce