Javascript solution using recursion


  • 0
    S

    Rarely see answer based on JS code, here we go:

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} p
     * @param {TreeNode} q
     * @return {boolean}
     */
    var isSameTree = function(p, q) {
        if (p === null && q === null) { return true; }
        if (p === null && q !== null) { return false; }
        if (p !== null && q === null) { return false; }
        if (p.val !== q.val) { return false; }
        
        var isLeftMatching = isSameTree(p.left, q.left);
        var isRightMatching = isSameTree(p.right, q.right);
        
        return isLeftMatching && isRightMatching;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.