404 Sum of Left Leaves 左叶子之和

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了404 Sum of Left Leaves 左叶子之和相关的知识,希望对你有一定的参考价值。

计算给定二叉树的所有左叶子之和。
示例:
    3
   / \\
  9  20
    /  \\
   15   7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24。

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

C++:

方法一:

/**
 * 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(!root||!root->left&&!root->right)
        {
            return 0;
        }
        int res=0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            root=que.front();
            que.pop();
            if(root->left&&!root->left->left&&!root->left->right)
            {
                res+=root->left->val;
            }
            if(root->left)
            {
                que.push(root->left);
            }
            if(root->right)
            {
                que.push(root->right);
            }
        }
        return res;
    }
};

 方法二:

/**
 * 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(!root)
        {
            return 0;
        }
        if(root->left&&!root->left->left&&!root->left->right)
        {
            return root->left->val+sumOfLeftLeaves(root->right);
        }
        return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
    }
};

 参考:https://www.cnblogs.com/grandyang/p/5923559.html

以上是关于404 Sum of Left Leaves 左叶子之和的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题-Sum of Left Leaves(Java实现)

[LeetCode] Sum of Left Leaves

404. Sum of Left Leaves

Leetcode 404. Sum of Left Leaves

#Leetcode# 404. Sum of Left Leaves

404. Sum of Left Leaves