fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Node n8 = new Node(4, null, null);
  14. Node n7 = new Node(7, null, null);
  15. Node n5 = new Node(5, n7, n8);
  16.  
  17. Node n6 = new Node(4, null, null);
  18.  
  19. Node n4 = new Node(2, null, null);
  20.  
  21. Node n2 = new Node(3, n4, n5);
  22. Node n3 = new Node(5, null, n6);
  23.  
  24. Node n1 = new Node(6, n2, n3);
  25.  
  26. System.out.println(getSum(n1));
  27. }
  28.  
  29. public static int getSum(Node head) {
  30. List<String> paths = getAllPaths(head);
  31.  
  32. int total = 0;
  33. for(String path : paths) {
  34. total += Integer.valueOf(path);
  35. }
  36. return total;
  37. }
  38.  
  39. private static List<String> getAllPaths(Node head) {
  40. if (head == null) {
  41. return null;
  42. }
  43.  
  44. List<String> left = getAllPaths(head.getLeft());
  45. List<String> right = getAllPaths(head.getRight());
  46.  
  47. List<String> results = new ArrayList<>();
  48. if (left == null && right == null) {
  49. results.add(String.valueOf(head.getData()));
  50. }
  51. if (right != null) {
  52. for (String path : right) {
  53. results.add(String.valueOf(head.getData()) + path);
  54. }
  55. }
  56. if (left != null) {
  57. for (String path : left) {
  58. results.add(String.valueOf(head.getData()) + path);
  59. }
  60. }
  61. return results;
  62. }
  63.  
  64. private static class Node {
  65. private final int data;
  66. private final Node left;
  67. private final Node right;
  68.  
  69. public Node(int data, Node left, Node right) {
  70. this.data = data;
  71. this.left = left;
  72. this.right = right;
  73. }
  74.  
  75. public int getData() {
  76. return this.data;
  77. }
  78.  
  79. public Node getLeft() {
  80. return this.left;
  81. }
  82.  
  83. public Node getRight() {
  84. return this.right;
  85. }
  86. }
  87. }
Success #stdin #stdout 0.06s 2184192KB
stdin
Standard input is empty
stdout
13997