|
| 1 | +packageAlgorithms.tree; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | + |
| 5 | +/* |
| 6 | + * |
| 7 | + * Sum Root to Leaf Numbers Total Accepted: 23940 Total Submissions: 80436 My Submissions |
| 8 | +Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. |
| 9 | +
|
| 10 | +An example is the root-to-leaf path 1->2->3 which represents the number 123. |
| 11 | +
|
| 12 | +Find the total sum of all root-to-leaf numbers. |
| 13 | +
|
| 14 | +For example, |
| 15 | +
|
| 16 | + 1 |
| 17 | + / \ |
| 18 | + 2 3 |
| 19 | +The root-to-leaf path 1->2 represents the number 12. |
| 20 | +The root-to-leaf path 1->3 represents the number 13. |
| 21 | +
|
| 22 | +Return the sum = 12 + 13 = 25. |
| 23 | + * */ |
| 24 | + |
| 25 | +publicclassSumNumbers { |
| 26 | +publicintsumNumbers(TreeNoderoot) { |
| 27 | +if (root ==null) { |
| 28 | +return0; |
| 29 | + } |
| 30 | + |
| 31 | +ArrayList<Integer>ret =newArrayList<Integer>(); |
| 32 | + |
| 33 | +// 存储从根节点到当前节点的路径上的数字 |
| 34 | +ArrayList<Integer>path =newArrayList<Integer>(); |
| 35 | + |
| 36 | +dfs(root,path,ret); |
| 37 | +intsum =0; |
| 38 | +for (intn:ret) { |
| 39 | +sum +=n; |
| 40 | + } |
| 41 | + |
| 42 | +returnsum; |
| 43 | + } |
| 44 | + |
| 45 | +publicvoiddfs(TreeNoderoot,ArrayList<Integer>path,ArrayList<Integer>ret) { |
| 46 | +if (root ==null) { |
| 47 | +return; |
| 48 | + } |
| 49 | + |
| 50 | +path.add(root.val); |
| 51 | + |
| 52 | +if (root.left ==null &&root.right ==null) { |
| 53 | +intnum =0; |
| 54 | +for (intn:path) { |
| 55 | +num =num *10 +n; |
| 56 | + } |
| 57 | +ret.add(num); |
| 58 | + }else { |
| 59 | +// 向左右子树递归 |
| 60 | +dfs(root.left,path,ret); |
| 61 | +dfs(root.right,path,ret); |
| 62 | + } |
| 63 | + |
| 64 | +// 一定要记得回溯,也就是说递归不能修改Path本身,否则以上向左右子树分别递归时 path就会被改。 |
| 65 | +path.remove(path.size() -1); |
| 66 | + } |
| 67 | +} |