LeetCode 404. Sum of Left Leaves 解题报告
题目描述
Find the sum of all left leaves in a given binary tree.
示例
限制条件
没有明确给出。
解题思路
我的思路:
对于这道题,我的思路是使用BFS访问树的节点,基于题目要求的是左叶子节点,关键的地方是怎样判断是左叶子节点。
判断的规则是如果某一节点的左子节点存在,并且该左子节点没有左右孙子节点,则该左子节点就是左叶子节点。
当满足上述规则时就加上该左子节点值,不满足就添加非空子节点到队列中,直到队列为空。
其他思路:
这道题目的难点也就是判断左子节点,实现方式除了BFS也可以用递归。
递归算法只要4行就可以完成。
代码
我的代码
/**
* 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;
int sum = 0;
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
TreeNode* cur = nodes.front();
nodes.pop();
if (cur->left) {
if (!(cur->left)->left && !(cur->left)->right)
sum += (cur->left)->val;
else
nodes.push(cur->left);
}
if (cur->right)
nodes.push(cur->right);
}
return sum;
}
};
参考代码
/**
* 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);
}
};
总结
也是树的题目,由于之前做过树的题目,BFS能够自己写出来了,这一点挺好的,要好好记住自己的实现过程,不要以后又忘了怎么写BFS。
又一个坑被填了,坚持!加油!