let say, we want to find the bottom left node in a tree.
one way to do it is using global vars:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{ public int findBottomLeftValue(TreeNode root)
{
find(root, 0);
return d_bottomLeft.val;
} private int d_bottomDepth = -1;
private TreeNode d_bottomLeft = null;
private void find(TreeNode node, int depth)
{
if (node == null) return;
if (depth >= d_bottomDepth)
{
d_bottomDepth = depth;
d_bottomLeft = node;
} find(node.right, depth + 1);
find(node.left , depth + 1);
}
}

to avoid using global vars, we can write it in this way:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{
public int findBottomLeftValue(TreeNode root)
{
Result result = new Result();
find(root, 0, result);
return result.d_bottomLeft.val;
} private void find(TreeNode node, int depth, Result result)
{
if (node == null) return;
if (depth >= result.d_bottomDepth)
{
result.d_bottomDepth = depth;
result.d_bottomLeft = node;
}
find(node.right, depth + 1, result);
find(node.left , depth + 1, result);
} private class Result
{
public int d_bottomDepth = -1;
public TreeNode d_bottomLeft = null;
}
}

最新文章

  1. CentOS 7 安装 配置 MySQL
  2. hadoop在网页客户端的maven配置
  3. myBatis foreach详解【转】
  4. 正则表达式regex狂记
  5. PHP json数据格式化方法
  6. 使用Python一步一步地来进行数据分析总结
  7. Selenium定位一 --单个元素定位方法
  8. activiti 源码笔记之startProcess
  9. Java菜鸟学习笔记--面向对象篇(十五):Wrapper Class包装类
  10. 内存管理——Cocos2d-x学习历程(五)
  11. 《JavaScript高级程序设计》读书笔记 ---执行环境及作用域
  12. PAT (Advanced Level) 1005. Spell It Right (20)
  13. android消息推送(Jpush)
  14. c++ 类的默认八种函数
  15. 【转载】XSS学习笔记
  16. Servlet3.0上传
  17. Spring Data JPA方法定义规范
  18. 跨域的根本原因:JavaScript 的同源策略
  19. JS模块化编程(四)--require应用
  20. 14)settings.xml

热门文章

  1. 【AHOI2009】中国象棋
  2. ie7 ie8 使用border模拟圆
  3. Java使用Jacob将Word、Excel、PPT转化成PDF
  4. Windows下允许redis远程访问
  5. python学习笔记6-输入输出与文件读取写入
  6. ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 02. Web Host 的默认配置
  7. python __builtins__ tuple类 (68)
  8. bzoj 2626: JZPFAR【KD-tree】
  9. 一篇文章搞定面试中的链表题目(java实现)
  10. C# BitmapData使用说明