题目来源:513. https://leetcode.com/problems/find-bottom-left-tree-value/description/
BFS基础训练。二叉树层次遍历,记录每一层。
513. Find Bottom Left Tree Value
题目大意
找出二叉树最底层最左边的元素的值。
Example 1:
Input:2 / \ 1 3Output:
1Example 2:
Input:1 / \ 2 3 / / \ 4 5 6 / 7Output:
7
思路
利用bfs实现层次遍历,非常经典了。
难度主要在记录二叉树的层数,friendbkf讲得相当清晰。
我复述一遍:
通过两个计数器curLevelCount 和 nextLevelCount 分别记录当前层的节点数和下一层的结点数。
每当有一个结点被弹出队列时,curLevelCount计数器就减一;每当有一个结点入队时,nextLevelCount 加一。
直到curLevelCount为0,表示该层所有结点都已经搜索完毕,则将nextLevelCount值赋给curLevelCount,进行下一层的搜索,接着不要忘了将nextLevelCount置为0。
记录每一层最先出队的元素的值,并在进入下一层时更换,最后得到的就是最底层最左边的元素的值。
解题代码
/**
* 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 findBottomLeftValue(TreeNode* root) {
int bottomLeftValue;
vector<int> values;
if (root == NULL) return 0;
queue<TreeNode*> myq;
myq.push(root);
int curLevelCount = 1;
int nextLevelCount = 0;
TreeNode* temp;
int levelCount = 0;
while (!myq.empty()) {
temp = myq.front();
myq.pop();
values.push_back(temp->val);
curLevelCount--;
if (temp->left != NULL) {
nextLevelCount++;
myq.push(temp->left);
}
if (temp->right != NULL) {
nextLevelCount++;
myq.push(temp->right);
}
if (curLevelCount == 0) {
curLevelCount = nextLevelCount;
nextLevelCount = 0;
levelCount++;
bottomLeftValue = values[0];
values.clear();
}
}
return bottomLeftValue;
}
};
本文介绍了解决LeetCode 513题“寻找二叉树最底层最左边的值”的方法。通过广度优先搜索(BFS)实现层次遍历,详细解释了如何记录每一层的节点数并获取最底层最左侧元素的值。

275

被折叠的 条评论
为什么被折叠?



