Fork me on GitHub

LeetCode404Sum of Left Leaves左叶子之和

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

示例:

       3

      / \

   9    20

         / \

     15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

 

 

 

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

posted @ 2018-10-23 21:12  lMonster81  阅读(97)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */