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。
考慮清楚遞歸的分界,最小情況是什么。