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 };

 

posted on 2017-05-03 08:52  无惧风云  阅读(138)  评论(0编辑  收藏  举报