【算法分析与设计】【第十五周】513. Find Bottom Left Tree Value
来源:互联网 发布:里德学院知乎 编辑:程序博客网 时间:2024/06/14 10:47
题目来源:513. https://leetcode.com/problems/find-bottom-left-tree-value/description/
- Find Bottom Left Tree Value
- 题目大意
- 思路
- 解题代码
BFS基础训练。二叉树层次遍历,记录每一层。
513. Find Bottom Left Tree Value
题目大意
找出二叉树最底层最左边的元素的值。
Example 1:
Input:2/ \1 3
Output:
1Example 2:
Input:1 / \ 2 3 / / \4 5 6 / 7
Output:
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; }};
阅读全文
0 0
- 【算法分析与设计】【第十五周】513. Find Bottom Left Tree Value
- 算法分析与设计第四周:513. Find Bottom Left Tree Value
- 第十周算法分析与设计: Find Bottom Left Tree Value
- 算法分析与设计丨第四周丨LeetCode(7)——Find Bottom Left Tree Value(Medium)
- LeetCode 513. Find Bottom Left Tree Value
- [leetcode]513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- [leetcode] 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 【LeetCode】513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- Leetcode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- [DFS]513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- Zookeeper ZAB 协议分析及算法
- 常见排序算法的讲解
- python下的manage 和进程池
- 分页前台
- 字符串格式化函数引起的崩溃
- 【算法分析与设计】【第十五周】513. Find Bottom Left Tree Value
- Spring中Bean的五个作用域
- 如何在一台window上创建多个MySQL服务
- 多进程三
- 第6章gp_toolkit管理架构-Checking Database Object Sizes and Disk Space
- 即将放弃Python 2.7的不止有Numpy,还有pandas和这些工具
- 工作一年的java技术员总结
- 2017年数据可视化的七大趋势!
- 大数问题(模板)