1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import java.util.ArrayList; import java.util.List;
class Node { int val; Node left; Node right;
public Node(int val) { this.val = val; } }
public class Main { private static List<Integer> list;
public static void main(String[] args) { Node n1 = new Node(1); Node n2 = new Node(5); Node n3 = new Node(1); Node root = new Node(1); Node o1 = new Node(2); Node o2 = new Node(2); root.left = o1; o1.left = n1; o1.right = n2; root.right = o2; o2.right = n3; list = new ArrayList<>(); int result = findBinaryTreeSum(root); System.out.println(result); }
private static int findBinaryTreeSum(Node root) { if (root == null) return 0; list.add(root.val); if (root.left == null && root.right == null) { int num = sumList(list); list.remove(list.size() - 1); return num; } else { int subSum = findBinaryTreeSum(root.left) + findBinaryTreeSum(root.right); list.remove(list.size() - 1); return subSum; } }
private static int sumList(List<Integer> list) { int num = 0; for (Integer integer : list) { num = num * 10 + integer; } return num; } }
|