404. Sum of Left Leaves

题目链接

Find the sum of all left leaves in a given binary tree.

Example:

1
2
3
4
5
6
7
    3
/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

如何确定左叶子节点,首先该节点必须是一个叶子节点,其次它必须位于其父节点的左子树上.当使用先序遍历时,该节点存在于左子树上且是一个叶子节点.

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
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeavesCore(root);
}
int sumOfLeftLeavesCore(TreeNode* root){
int sum = 0;
stack<TreeNode*> st;
TreeNode* cur = root;
while(cur!=nullptr || !st.empty()){
if(cur == nullptr){
cur = st.top();
st.pop();
cur = cur->right;
}else{
st.push(cur);
cur = cur->left;
if(cur && cur->left == nullptr && cur->right == nullptr){
sum += cur->val;
}
}
}
return sum;
}
};