Coding Spirit

一位程序员,比较帅的那种

0%

Algorithm Puzzles: Sum of Left Leaves

Algorithm Puzzles everyday every week sometimes: Sum of Left Leaves

Puzzle

Puzzle from leetcode:

Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Solution

It’s an easy puzzle can be resolved via dfs or bfs, here I use bfs:

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
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;

if (root == nullptr) {
return sum;
}

std::queue<TreeNode*> q;
std::queue<bool> isLeftNode;

q.push(root);
isLeftNode.emplace(false);

while (!q.empty()) {
auto cur = q.front();
if (cur->left == nullptr && cur->right == nullptr &&
isLeftNode.front()) {
sum += cur->val;
}
q.pop();
isLeftNode.pop();

if (cur->left != nullptr) {
q.push(cur->left);
isLeftNode.emplace(true);
}
if (cur->right != nullptr) {
q.push(cur->right);
isLeftNode.emplace(false);
}
}

return sum;
}
};

TC should be O(n) and SC should be O(n) in worst case, where n is node number.