JavaScript Recursion


  • 0
    W

    DFS down the tree while keeping track of the previous (parent) node. If there are no more children nodes remaining, then we've encountered a leaf. At this point, check if the current node is the left child of the parent node. If so, add its own value to the sum.

    function sumOfLeftLeaves(root, up, sum) {
        
        sum = sum || 0;
        
        if (!root) return sum;
        if (!root.left && !root.right) {
            if (up && up.left == root) {
                return root.val + sum;
            }
        }
        
        return sumOfLeftLeaves(root.left, root, sum) + sumOfLeftLeaves(root.right, root, sum);
        
    };
    

Log in to reply
 

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