-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path1302-deepest-leaves-sum.js
More file actions
41 lines (36 loc) · 930 Bytes
/
1302-deepest-leaves-sum.js
File metadata and controls
41 lines (36 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 1302. Deepest Leaves Sum
* https://leetcode.com/problems/deepest-leaves-sum/
* Difficulty: Medium
*
* Given the root of a binary tree, return the sum of values of its deepest leaves.
*/
/**
* 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 maxDepth = 0;
let sumAtMaxDepth = 0;
function traverse(node, depth) {
if (!node) return;
if (depth > maxDepth) {
maxDepth = depth;
sumAtMaxDepth = node.val;
} else if (depth === maxDepth) {
sumAtMaxDepth += node.val;
}
traverse(node.left, depth + 1);
traverse(node.right, depth + 1);
}
traverse(root, 0);
return sumAtMaxDepth;
};