zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Angularjs中的ng-class
    AngularJS 的表单验证
    Eclipse更新慢、插件安装慢解决方案zz
    PSD的单位及计算方法[转]
    .NET控件名称缩写一览表 zz
    C#Stopwatch的简单计时zz
    VsVim的快捷键
    MySQL-mysql 8.0.11安装教程
    使用open live writer客户端写博客zz
    WPFToolkit DataGrid 使用介绍zz
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8855233.html
Copyright © 2011-2022 走看看