1.题目
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.code
/**
* 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) {
stack<TreeNode*>s;
TreeNode* p;
int sum=0;
p=root;
while(p||!s.empty())
{
while(p)
{
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
s.pop();
if(p->left!=NULL&&p->left->left==NULL&&p->left->right==NULL)
{
sum+=p->left->val;
}
p=p->right;
}
}
return sum;
}
};
3.分析
先序遍历,加一个判断条件加和就可以。如果是左节点并且是叶子节点。