博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于Java对象引用的理解
阅读量:4131 次
发布时间:2019-05-25

本文共 1855 字,大约阅读时间需要 6 分钟。

LeetCode题目描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

1   / \  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

我的思路:

就像之前的找所有根到叶子的路径问题,把所有路径找出来再算,于是写了如下代码

public int sumNumbers(TreeNode root) {        List
> res = new ArrayList(); List
list = new ArrayList(); int sum = 0; go(root,res,list); for(int i = 0;i < res.size();i++){ List
tem = res.get(i); int time = 0; for(int k = tem.size()-1;k >= 0;k--){ int num = tem.get(k); System.out.println(num); int ti = time; while(ti > 0){ num = num*10; ti --; } sum += num; time++; } } return sum; } public void go(TreeNode t,List
> res,List
list){ if(t == null)return; list.add(t.val); if(t.left==null&&t.right==null){ res.add(list); //System.out.println(res); list.remove(list.size()-1); //System.out.println(res); return; } go(t.left,res,list); go(t.right,res,list); list.remove(list.size()-1); }

问题来了

上述代码运行之后 结果为0,sysout之后发现res,list为空。为什么呢?
注意获得res的go函数中

if(t.left==null&&t.right==null){            res.add(list);            //System.out.println(res);            list.remove(list.size()-1);            //System.out.println(res);            return; }
把list添加到res中了,然后退出函数之前删掉进来的这个节点,思路没问题,但是,加入res的是list引用,相当于res(i)--->list,之后对list进行操作,list改变res对应位置也会改变。

所以改为res.add(new ArrayList(list));相当于复制对象。

转载地址:http://qhdvi.baihongyu.com/

你可能感兴趣的文章
数据库
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python实现100以内自然数之和,偶数之和
查看>>
python数字逆序输出及多个print输出在同一行
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>
vue 遍历对象并动态绑定在下拉列表中
查看>>
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>
python __future__
查看>>
MySQL Tricks1
查看>>
python 变量作用域问题(经典坑)
查看>>
pytorch
查看>>
pytorch(三)
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>