-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum-of-left-leaves.js
46 lines (44 loc) · 1.07 KB
/
sum-of-left-leaves.js
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
/**
* 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 sumOfLeftLeaves = function (root) {
// 前序遍历 递归
let sum = 0;
const preOrderTraverse = (node) => {
if (node) {
// 判断是否是左叶子节点
if (node.left && !node.left.left && !node.left.right) {
sum += node.left.val;
}
preOrderTraverse(node.left);
preOrderTraverse(node.right);
}
};
preOrderTraverse(root);
return sum;
// 前序遍历 迭代
// return preOrder(root);
};
function preOrder(root) {
const stack = [root];
let sum = 0;
while (stack.length) {
const node = stack.pop();
// left leaf node
if (node.left && !node.left.left && !node.left.right) {
sum += node.left.val;
}
node.right && stack.push(node.right);
node.left && stack.push(node.left);
}
return sum;
}