Problem:
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Return 24.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
Solution:
Recursive solution:
检查当前节点的左子节点是否是左子叶,如果是的话,返回左子叶的值加上对当前结点的右子节点调用递归的结果;如果不是的话,对左右子节点分别调用递归函数,返回二者之和。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left && !root->left->left && !root->left->right)
{ //if left child is a leaf
return root->left->val + sumOfLeftLeaves(root->right);
}
else return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
Iterative solution:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) return 0;
int result = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode *t = q.front();
q.pop();
if (t->left && !t->left->left && !t->left->right)
{ //if left child is a leaf
result += t->left->val;
}
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
return result;
}
};
Memo:
读清题意,left leaves。
考虑清楚递归的分界,最小情况是什么。