一、題目介紹
計算給定二叉樹的所有左葉子之和。
示例:
3
/ \
9 20
/ \
15 7
在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sum-of-left-leaves
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
二、解題思路
利用遞歸的方式,找到所有左邊的葉子節點然後再求和。判斷當前節點是否爲左邊的葉子節點需要兩個條件:(1)當前節點爲其父節點的左節點;(2)當前節點爲葉子節點。具體實現詳見代碼。
三、解題代碼
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = 0;
int sumOfLeftLeaves(TreeNode* root) {
if(root)
{
if(root->left && root->left->left == NULL && root->left->right == NULL)
res += root->left->val;
sumOfLeftLeaves(root->left);
sumOfLeftLeaves(root->right);
}
return res;
}
};