解题思路:
用bfs的方法,利用队列,将每一层的节点放入队列中,每次记录每一层第一个节点的值,一直遍历直到队列为空,代码如下:
代码
/**
* 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) {
queue<TreeNode*> q;
q.emplace(root);
int ans = 0;
while(!q.empty()) {
int n = q.size();
for(int i = 0; i < n; i ++) {
TreeNode* node = q.front();
q.pop();
if(i == 0) {
ans = node->val;
}
if(node->left != nullptr) q.emplace(node->left);
if(node->right != nullptr) q.emplace(node->right);
}
}
return ans;
}
};