-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1302.层数最深叶子节点的和.js
More file actions
51 lines (47 loc) · 1.16 KB
/
1302.层数最深叶子节点的和.js
File metadata and controls
51 lines (47 loc) · 1.16 KB
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
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode.cn id=1302 lang=javascript
*
* [1302] 层数最深叶子节点的和
*/
const { node } = require("prop-types");
// @lc code=start
/**
* 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 level = 0
function findMaxDep(node, currentLevel) {
if(!node) {
return
}
level = Math.max(level, currentLevel)
findMaxDep(node.left, currentLevel + 1)
findMaxDep(node.right, currentLevel + 1)
}
findMaxDep(root, 0)
const stack = []
stack.push({
node: root,
level: 0
})
let result = 0
while (stack.length) {
const current = stack.pop()
if(current.level === level) {
result += current.node.val
}
current.node.left && stack.push({ node: current.node.left, level: current.level + 1 })
current.node.right && stack.push({ node: current.node.right, level: current.level + 1 })
}
return result
};
// @lc code=end