Sum of Left Leaves

404.Sum of Left Leaves

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.

Example 1:

img

1
2
3
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:

1
2
Input: root = [1]
Output: 0

深度优先遍历:

时间复杂度:O(n)

空间复杂度:O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isLeafNode(TreeNode* node) {
return !node->left && !node->right;
}

int dfs(TreeNode* node) {
int ans = 0;
if (node->left) {
ans += isLeafNode(node->left) ? node->left->val : dfs(node->left);
}
if (node->right && !isLeafNode(node->right)) {
ans += dfs(node->right);
}
return ans;
}

int sumOfLeftLeaves(TreeNode* root) {
return root ? dfs(root) : 0;
}
};

广度优先遍历:

时间复杂度:O(n)

空间复杂度:O(n)

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
class Solution {
public:
bool isLeafNode(TreeNode* node) {
return !node->left && !node->right;
}

int sumOfLeftLeaves(TreeNode* root) {
if (!root) {
return 0;
}

queue<TreeNode*> q;
q.push(root);
int ans = 0;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node->left) {
if (isLeafNode(node->left)) {
ans += node->left->val;
}
else {
q.push(node->left);
}
}
if (node->right) {
if (!isLeafNode(node->right)) {
q.push(node->right);
}
}
}
return ans;
}
};