Why return false when root == null


  • 0
    K

    Code below is in javascript:

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @param {number} sum
     * @return {boolean}
     */
    var hasPathSum = function(root, sum) {
       if(root === null) return false
       var result = 0
       return helper(root, result, sum)
    };
    
    function helper(root, result, sum){
        if(root === null) return false //why?????????????????????
        result += root.val
        if(root.left === null && root.right === null){
            return result === sum
        }
        return helper(root.left, result, sum) || helper(root.right, result, sum)
    }

  • 0

    You're asking us why you return null there?


  • 0
    K

    this is an answer i found online


  • 0

    You should say that in the question, to avoid confusion and the plagiarism. Preferably with a link to the source. Or better yet, why don't you ask right where it was posted? Then there's context there already, plus the author will be notified.


  • 0
    C

    return false because you can not find sum to match in null/empty tree. it has test case like ([] 1).


Log in to reply
 

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