关于Java对象引用的理解

xiaoxiao2021-02-28  122

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<List<Integer>> res = new ArrayList(); List<Integer> list = new ArrayList(); int sum = 0; go(root,res,list); for(int i = 0;i < res.size();i++){ List<Integer> 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<List<Integer>> res,List<Integer> 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));相当于复制对象。

转载请注明原文地址: https://www.6miu.com/read-44725.html

最新回复(0)