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