Find Bottom Left Tree Value
来源:互联网 发布:怎么分辨mac口红真假 编辑:程序博客网 时间:2024/06/05 09:32
题目:
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
这道题让我们求二叉树的最左下树结点的值,就是最后一行左边第一个结点的值。
解题思路:
首先想到是用先序遍历来做,因为先序遍历遍历的顺序是左-根-右,所以每一行最左边的结点肯定最先遍历到,那么由于
是新一行,那么当前深度肯定比之前的最大深度大,所以可以更新最大深度为当前深度,结点值result为当前结点值。
但是使用广度优先搜索,对每一层进遍历更简单,result每次保存每一层的第一个值,最后层序遍历完成之后的result即为
最后一行的第一个结点的值。
代码如下:
int findBottomLeftValue(TreeNode* root) {
int result = root->val;
queue<TreeNode *> q;
q.push(root);
TreeNode* temp;
while (!q.empty()) {
int size = q.size();
result = q.front()->val;
while (size--) {
temp = q.front();
q.pop();
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
}
return result;
}
};
0 0
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- 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
- 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
- C语言实验——打印数字图形
- 替换空格
- Octave入门基础
- javascript构造函数之稳妥构造函数
- 493_有头尾布局的条目点击
- Find Bottom Left Tree Value
- .NET 分层开发 第一二章学生管理系统
- Oracle12C--序列(十六)
- 任务分发框架 gearmand
- 494_桌面悬浮窗
- Android开发:最全面、最易懂的Android屏幕适配解决方案
- InnoDB存储引擎——表
- PHP
- iOS导航栏切换界面时隐藏和显示