-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumofLeftLeaves.js
More file actions
47 lines (42 loc) · 1.24 KB
/
sumofLeftLeaves.js
File metadata and controls
47 lines (42 loc) · 1.24 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
////////////////////////////////////////////////Sum of Left Leaves///////////////////////////////////////////
// Given the root of a binary tree, return the sum of all left leaves.
// Example 1:
// Input: root = [3,9,20,null,null,15,7]
// Output: 24
// Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
// Example 2:
//
// Input: root = [1]
// Output: 0
/**
* 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}
*/
const sumOfLeftLeaves = function(root) {
const queue = [root];
let sum = 0;
while (queue.length > 0) {
const current = queue.shift();
if (current.left) {
if (!current.left.left && !current.left.right) {
sum += current.left.val;
} else {
queue.push(current.left);
}
}
if (current.right) {
queue.push(current.right);
}
}
return sum;
};
// console.log(sumOfLeftLeaves([3,9,20,null,null,15,7]));
// console.log(sumOfLeftLeaves([1]));