404. 左叶子之和

计算给定二叉树的所有左叶子之和。

解:
1代表左节点,0代表右节点

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root==NULL)
            return 0;
        return sum_Left(root,0);
        
    }
private:
    int sum_Left(TreeNode* root,int flag)
    {
        if(root->left==NULL&&root->right==NULL)
            return flag==1?root->val:0;
        int sum=0;
        if(root->left!=NULL)
            sum+=sum_Left(root->left,1);
        if(root->right!=NULL)
            sum+=sum_Left(root->right,0);
        return sum;
    }
    
};

你可能感兴趣的:(404. 左叶子之和)