[LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
2017-02-16 12:28
477 查看
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Example 2:
Note: You may assume the tree (i.e., the given root node) is not NULL.
这道题让我们求二叉树的最左下树结点的值,也就是最后一行左数第一个值,那么我首先想的是用先序遍历来做,我们维护一个最大深度和该深度的结点值,由于先序遍历遍历的顺序是根-左-右,所以每一行最左边的结点肯定最先遍历到,那么由于是新一行,那么当前深度肯定比之前的最大深度大,所以我们可以更新最大深度为当前深度,结点值res为当前结点值,这样在遍历到该行其他结点时就不会更新结果res了,参见代码如下:
解法一:
其实这道题用层序遍历更直接一些,因为层序遍历时遍历完当前行所有结点之后才去下一行,那么我们再遍历每行第一个结点时更新结果res即可,根本不用维护最大深度了,参见代码如下:
解法二:
参考资料:
https://discuss.leetcode.com/topic/78954/verbose-java-solution-binary-tree-level-order-traversal
LeetCode All in One 题目讲解汇总(持续更新中...)
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.
这道题让我们求二叉树的最左下树结点的值,也就是最后一行左数第一个值,那么我首先想的是用先序遍历来做,我们维护一个最大深度和该深度的结点值,由于先序遍历遍历的顺序是根-左-右,所以每一行最左边的结点肯定最先遍历到,那么由于是新一行,那么当前深度肯定比之前的最大深度大,所以我们可以更新最大深度为当前深度,结点值res为当前结点值,这样在遍历到该行其他结点时就不会更新结果res了,参见代码如下:
解法一:
class Solution { public: int findBottomLeftValue(TreeNode* root) { if (!root) return 0; int max_depth = 1, res = root->val; helper(root, 1, max_depth, res); return res; } void helper(TreeNode* node, int depth, int& max_depth, int& res) { if (!node) return; if (depth > max_depth) { max_depth = depth; res = node->val; } helper(node->left, depth + 1, max_depth, res); helper(node->right, depth + 1, max_depth, res); } };
其实这道题用层序遍历更直接一些,因为层序遍历时遍历完当前行所有结点之后才去下一行,那么我们再遍历每行第一个结点时更新结果res即可,根本不用维护最大深度了,参见代码如下:
解法二:
class Solution { public: int findBottomLeftValue(TreeNode* root) { if (!root) return 0; int res = 0; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; ++i) { TreeNode *t = q.front(); q.pop(); if (i == 0) res = t->val; if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return res; } };
参考资料:
https://discuss.leetcode.com/topic/78954/verbose-java-solution-binary-tree-level-order-traversal
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- Android属性之build.prop生成过程分析
- 基于GPUImage的自定义相机 --- 拍照录像
- priority_queue
- CocoaPods 导库时提示“Use the `$(inherited)` flag” or “Remove the build settings from the target”
- MFC .sbr': No such file or directory 空工大 clean rebuild all出错
- error: uuid/uuid.h: No such file or directory
- Flask 用Blueprint实现模块化的应用
- LeetCode Longest Increasing Subsequence
- Vue - 起手式
- UE4 委托应用
- LintCode Longest Increasing Continuous Subsequence
- 设计模式之-迭代器(Iterator)模式 + 建造者(Build)模式
- OAI eNB + srsUE + Amarisoft MME成功调通
- iOS学习-tableView下拉刷新(UIRefreshControl)
- key-value的topK问题
- SPOJ DRUIDEOI (单调栈)
- sequel pro无法连接mysql服务器
- Mosquitto搭建Android推送服务(二)Mosquitto简介及搭建
- Errors while building APK. You can find the errors in the 'Messages' view
- Electron学习笔记Part3-利用Electron builder应用打包EXE