美文网首页
404. 左叶子之和

404. 左叶子之和

作者: 小时候浪死了 | 来源:发表于2018-10-21 11:37 被阅读0次

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

    解:
    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. 左叶子之和

          本文链接:https://www.haomeiwen.com/subject/iarvzftx.html