image.png

思路:

  • 依然是标准的层次遍历二叉树
  • 采用了for循环,i == 0 的时候,必然就是最左边的数值,而最后一次更新的“最左边的数值”,就是最底层的最左边的数值

代码:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. int findBottomLeftValue(TreeNode* root) {
  15. int bottom_left = 0;
  16. queue<TreeNode*> q;
  17. q.push(root);
  18. while (!q.empty()) {
  19. int cur_level_size = q.size();
  20. for (int i = 0; i < cur_level_size; ++i) {
  21. TreeNode* node = q.front();
  22. q.pop();
  23. if (i == 0) {
  24. bottom_left = node->val;
  25. }
  26. if (node->left) q.push(node->left);
  27. if (node->right) q.push(node->right);
  28. }
  29. }
  30. return bottom_left;
  31. }
  32. };