关于Java对象引用的理解

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));相当于复制对象。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值