JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int sumNumbers(TreeNode root) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         ArrayList<Integer> result = new ArrayList<Integer>();
15         if(root == null)
16             return 0;
17         dfs(result, 0, root);
18         int sum = 0;
19         for(int i:result)
20             sum += i;
21         return sum;
22     }
23     
24     private void dfs(ArrayList<Integer> result, int now, TreeNode root){
25         if(root.left == null && root.right == null){
26             result.add(10*now+root.val);
27             return;
28         }
29         now = now * 10 + root.val;
30         if(root.left!=null)
31             dfs(result, now, root.left);
32         if(root.right!=null)
33             dfs(result, now, root.right);
34     }
35 }

 

 

posted on 2013-11-07 08:42  JasonChang  阅读(170)  评论(0编辑  收藏  举报