思路:
- 依然是标准的层次遍历二叉树
- 采用了for循环,
i == 0
的时候,必然就是最左边的数值,而最后一次更新的“最左边的数值”,就是最底层的最左边的数值
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int bottom_left = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int cur_level_size = q.size();
for (int i = 0; i < cur_level_size; ++i) {
TreeNode* node = q.front();
q.pop();
if (i == 0) {
bottom_left = node->val;
}
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return bottom_left;
}
};