404 左叶子之和
题目:
给定二叉树的根节点 root ,返回所有左叶子之和。


实例:
image.png


提示:

  • 节点数在 [1, 1000] 范围内
  • -1000 <= Node.val <= 1000

题解:
关键在于判断左节点是否为左叶子节点:
image.png

方法二:广度优先搜索

  1. class Solution {
  2. public:
  3. bool isLeafNode(TreeNode* node) {
  4. return !node->left && !node->right;
  5. }
  6. int sumOfLeftLeaves(TreeNode* root) {
  7. if (!root) {
  8. return 0;
  9. }
  10. queue<TreeNode*> q;
  11. q.push(root);
  12. int ans = 0;
  13. while (!q.empty()) {
  14. TreeNode* node = q.front();
  15. q.pop();
  16. if (node->left) {
  17. if (isLeafNode(node->left)) {
  18. ans += node->left->val;
  19. }
  20. else {
  21. q.push(node->left);
  22. }
  23. }
  24. if (node->right) {
  25. if (!isLeafNode(node->right)) {
  26. q.push(node->right);
  27. }
  28. }
  29. }
  30. return ans;
  31. }
  32. };

今日意外,搞笑评论区:
某位网友在评论区的发言:
image.png
以及她获得的回复:
image.pngimage.pngimage.png
有点心疼这位发表评论的友友了,不过,真的好好笑😂