MDGSF Software Engineer

[算法学习][leetcode] 404 Sum of Left Leaves

2017-08-31
mdgsf
Art

https://leetcode.com/problems/sum-of-left-leaves/description/

题目

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题目翻译

题目解析

参考答案

#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:

    bool bIsLeaves(TreeNode * node)
    {
        if (NULL == node)
        {
            return false;
        }

        if (node->left == NULL && node->right == NULL)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    int sumOfLeftLeavesRecur(TreeNode* root) {

        if (NULL == root)
        {
            return 0;
        }

        if (bIsLeaves(root))
        {
            return root->val;
        }

        int iLeftSum = sumOfLeftLeavesRecur(root->left);
        int iRightSum = sumOfLeftLeavesRecur(root->right);
        if (bIsLeaves(root->right))
        {
            iRightSum -= root->right->val;
        }

        return iLeftSum + iRightSum;
    }

    int sumOfLeftLeaves(TreeNode* root) {

        if (NULL == root)
        {
            return 0;
        }

        if (bIsLeaves(root))
        {
            return 0;
        }

        return sumOfLeftLeavesRecur(root);
    }
};

int main()
{
    return 0;
}
/**
 * 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 sumOfLeftLeaves(TreeNode* root) {
        if(NULL == root)
        {
            return 0;
        }

        int iSum = 0;
        if(root->left != NULL && (root->left->left == NULL && root->left->right == NULL))
        {
            iSum = root->left->val;
        }

        return iSum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
    }

};

weixingongzhonghao

Similar Posts

Comments