Given a binary tree, find the leftmost value in the last row of the tree.

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.

--------------------------------------------------------------------------------------------------------------------------------

这个题就是求出二叉树的最后一层的最左边的结点的数。

可以用BFS,也可以用DFS,不过BFS相对会简单一些的。

C++代码:

/**
* 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) {
if(!root) return ;
queue<TreeNode*> q;
q.push(root);
int res = root->val;
while(!q.empty()){
int len = q.size(); //必须加上这个,如果用i==q.size(),则会出错,因为q.size()会变化。
for(int i = len; i > ; i--){
auto t = q.front();
q.pop();
if(i == len){
res = t->val;
}
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
};

最新文章

  1. Jenkins&mdash;&mdash;构建、集成中的问题
  2. UICollectionView 自定义组头组尾的XIB方法
  3. 用typedef自定义类型语法你真的会吗
  4. HTML 表单和验证事件
  5. 解决AndroidADT自带Eclipse编辑器不能自动代码提示的问题
  6. 给animator动态添加事件
  7. HBase 建表新增数据记录
  8. poj 2887 Big String
  9. 和阿文一起学H5--如何把H5压缩到最小
  10. Appcn 移动开发 前台与服务器数据交互
  11. Web前端新人笔记之CSS字体
  12. 关于c语言不定参数的研究
  13. C++刷称号——2707: 素数与要素
  14. ubutu下的几个命令
  15. WPF水珠效果按钮组
  16. 高通HAL层之Sensor HAL
  17. [随笔][Java][something]
  18. Codeforces Round #436 C. Bus
  19. Json传递数据两种方式(json大全)
  20. I/O系统(一)

热门文章

  1. C#使用MemoryStream类读写内存
  2. codeforces982F
  3. YUV格式与RGB格式
  4. Civil 3D 二次开发 新建CLR项目出现错误C2143
  5. C#常忘语法笔记(C#程序设计基础1-4章)
  6. luogu P1353 【[USACO08JAN]跑步Running】
  7. BZOJ1208[HNOI2004]宠物收养场——treap
  8. 基于网络编程 TCP协议 及 socket 基本语法
  9. Iroha and a Grid AtCoder - 1974(思维水题)
  10. 【XSY2679】修墙 最短路