알고리즘 공부 2020. 8. 20. 22:33

https://leetcode.com/problems/deepest-leaves-sum/

 

Deepest Leaves Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * 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) {
    const sums = Array(Math.pow(10,3)).fill(0);
    let maxdepth = 0;
    const find = function( p_root, p_depth )
    {
        if( p_root )
        {
            sums[p_depth] += p_root.val;            
            
            find( p_root.left, p_depth+1)
            find( p_root.right, p_depth+1)
        }
        else
        {
            maxdepth = Math.max( maxdepth, p_depth-1 );
        }
    }
    find( root, 1 );
    
    return sums[maxdepth];
};
posted by Sense.J
: