404. Sum of Left Leaves
Description
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.
Solution
- 題意即求和作爲左子樹的葉子結點的值。
- 整體解題思想是遍歷但是不遍歷右葉子,如果當前是葉子結點,那麼一定是左葉子,那麼累和。
- 我採用的是中序遍歷的方式,對於左子樹遍歷,可以放心大膽,因爲不會遍歷到右葉子,然後判斷當前根節點,如果是葉子那麼累和,對於右子樹遍歷,需要確認該右子樹不是葉節點才能繼續遍歷,代碼如下。
class Solution {
public:
int rnt = 0;
void travel(TreeNode *root) {
if (!root) return ;
travel(root->left);
if (!root->left && !root->right) rnt += root->val;
if ((root->right) && (root->right->left || root->right->right)) travel(root->right);
}
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) return 0;
travel(root);
return rnt;
}
};