JavaScript Solution


  • 0
    A
    var isSameTree = function(p, q) {
        var result = true;
        
        var compare = function(nodeP, nodeQ) {
          if (
              (nodeP !== null && nodeQ === null) ||
              (nodeP === null && nodeQ !== null)
             ) {
            result = false;
            return;
          }
          result = result && nodeP.val === nodeQ.val;
        }
        
        var walk = function(nodeP, nodeQ) {
            if (nodeP !== null || nodeQ !== null) {
                compare(nodeP, nodeQ);
                walk(nodeP ? nodeP.left : null, nodeQ ? nodeQ.left : null);
                walk(nodeP ? nodeP.right : null, nodeQ ? nodeQ.right : null);
            }
        }
        
        walk(p, q);
        
        return result;
    };
    

  • 0
    A

    I like this solution better: https://discuss.leetcode.com/topic/105644/accepted-solution.

    I converted to JavaScript and the following ran in 96ms which is 33% faster than my solution which ran in 128ms.

    var isSameTree = function(p, q) {
        if (p === null && q === null) return true;
        if (p === null || q === null) return false;
        if (p.val === q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        return false;
    };
    

Log in to reply
 

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