Javascript solution using recursion


  • 0
    S
    /**
     * 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) {
        return helper(root, 0, sum);
    };
    
    var helper = function(root, curSum, sum) {
        if (!root) { return false; }
        if (root.left === null && root.right === null) {
            curSum += root.val;
            return curSum === sum;
        }
        
        return helper(root.left, curSum + root.val, sum) || helper(root.right, curSum + root.val, sum);
    };
    

Log in to reply
 

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