• 404. Sum of Left Leaves(LeetCode)


    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.
    注:只求叶子的和!!
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int sumOfLeftLeaves(TreeNode* root) {
    13         if (root == NULL)
    14             return 0;
    15         else
    16         return sumleft(root);
    17     }
    18     int sumleft(TreeNode* root)
    19     {
    20         int sum=0;
    21         stack<TreeNode*> sta;
    22         sta.push(root);
    23         while (sta.size())
    24         {
    25             TreeNode* pNode = sta.top();
    26             sta.pop();
    27             if (pNode->right)
    28                 sta.push(pNode->right);
    29             if (pNode->left)
    30             {
    31                 sta.push(pNode->left);
    32                 if (pNode->left->left == NULL&&pNode->left->right == NULL)
    33                 sum += pNode->left->val;
    34             }
    35             
    36         }
    37         return sum;
    38     }
    39 };
  • 相关阅读:
    Windows安装node.js
    02ARM体系结构
    01ARM介绍
    01软件过程模型
    创建一个JavaWeb工程
    python之面向对象01
    python学生管理系统
    python文件、文件夹的相关操作
    python文件的定位读写
    python文件的写入与备份
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6800112.html
Copyright © 2020-2023  润新知