Leetcode #1302 Deepest Leaves Sum

Leetcode #1302 Deepest Leaves Sum

Difficulty: Medium

We can use recursion to solve this, traversing the tree DFS.

Thought process:

  • Traverse the tree and increasing the depth each time
  • If we found the leaf node, keep track of the maximum depth
  • If we are already at the maximum depth, we increase our sum (because that is essentially the leaf node)

Link: Deepest Leaves Sum

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var deepestLeavesSum = function(root) {
    let sum = 0;
    let depth = 0;
    let maxDepth = 0;

    let traverse = (node, depth) => {
        if(!node) return;

        if(!node.left && !node.right){
            if(depth > maxDepth){
                sum = node.val;
                maxDepth = depth;
            }else if(depth === maxDepth){
                sum += node.val;
            }
        }else{
            traverse(node.left, depth+1)
            traverse(node.right, depth+1)    
        }
    }

    traverse(root, 0)

    return sum;
};