1.题目描述
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.
来自 <https://leetcode.com/problems/sum-of-left-leaves/description/>
2.问题分析
找出所有的左叶子结点,并求和,同样是用深度优先遍历方式,比较简单。
2.C++代码
//我的代码:(beats 94%)
//DFS
int sumOfLeftLeaves(TreeNode* p)
{
if (p == NULL)
return 0;
int sum = 0;
stack<TreeNode*>s;
while (!s.empty() || p != NULL)
{
while (p)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
s.pop();
if (p->left&&p->left->left == NULL&&p->left->right == NULL)//左叶子
{
sum += p->left->val;
cout<< p->left->val<<endl;
}
p = p->right;
}
}
return sum;
}
既然DFS可以,那么BFS也可以
//BFS
int sumOfLeftLeaves2(TreeNode* p)
{
if (p == NULL)
return 0;
int sum = 0;
queue<TreeNode*> q;
q.push(p);
while (!q.empty())
{
TreeNode *tmp = q.front();
q.pop();
if (tmp->left)
{
q.push(tmp->left);
if (tmp->left->left == NULL&&tmp->left->right == NULL)
{
sum += tmp->left->val;
cout << tmp->left->val << endl;
}
}
if (tmp->right)
q.push(tmp->right);
}
return sum;
}
试试递归
//递归
int sumOfLeftLeaves(TreeNode* p)
{
int sum = 0;
if (p == NULL)
return 0;
if (p->left)
{
if (p->left->left == NULL&&p->left->right == NULL)
{
sum += p->left->val;
cout << p->left->val << endl;;
}
sum += sumOfLeftLeaves(p->left);
}
if(p->right)
sum+=sumOfLeftLeaves(p->right);
return sum;
}