how to make a function from using global var to not using it
2024-08-26 03:05:17
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;
}
}
最新文章
- CentOS 7 安装 配置 MySQL
- hadoop在网页客户端的maven配置
- myBatis foreach详解【转】
- 正则表达式regex狂记
- PHP json数据格式化方法
- 使用Python一步一步地来进行数据分析总结
- Selenium定位一 --单个元素定位方法
- activiti 源码笔记之startProcess
- Java菜鸟学习笔记--面向对象篇(十五):Wrapper Class包装类
- 内存管理——Cocos2d-x学习历程(五)
- 《JavaScript高级程序设计》读书笔记 ---执行环境及作用域
- PAT (Advanced Level) 1005. Spell It Right (20)
- android消息推送(Jpush)
- c++ 类的默认八种函数
- 【转载】XSS学习笔记
- Servlet3.0上传
- Spring Data JPA方法定义规范
- 跨域的根本原因:JavaScript 的同源策略
- JS模块化编程(四)--require应用
- 14)settings.xml
热门文章
- 【AHOI2009】中国象棋
- ie7 ie8 使用border模拟圆
- Java使用Jacob将Word、Excel、PPT转化成PDF
- Windows下允许redis远程访问
- python学习笔记6-输入输出与文件读取写入
- ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 02. Web Host 的默认配置
- python __builtins__ tuple类 (68)
- bzoj 2626: JZPFAR【KD-tree】
- 一篇文章搞定面试中的链表题目(java实现)
- C# BitmapData使用说明