左叶子之和
力扣题目链接
题目描述
给定二叉树的根节点 root ,返回所有左叶子之和。
解题思路
层次遍历的时候,保留每层第一个节点并相加即可。
题解
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL){
return 0;
}
return func(root, false);
}
int func(TreeNode* root, bool isLeft){
int ans = 0;
if(root->left){
ans += func(root->left, true);
}
if(root->right){
ans += func(root->right, false);
}
if(!root->left && !root->right && isLeft){
ans += root->val;
}
return ans;
}
};