fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. class Main{
  5. static class Node{
  6. Node right;
  7. Node left;
  8. int data;
  9. Node(int data){
  10. this.data = data;
  11. }
  12. }
  13. static Node buildtree(int[]vals){
  14. if(vals.length==0 || vals[0] == -1) return null;
  15. Node root = new Node(vals[0]);
  16. Queue<Node> q = new LinkedList<>();
  17. q.offer(root);
  18. int i = 1;
  19. while(!q.isEmpty()&&i<vals.length){
  20. Node curr = q.poll();
  21. if(i<vals.length && vals[i]!= -1){
  22. curr.left = new Node(vals[i]);
  23. q.offer(curr.left);
  24. }i++;
  25. if(i<vals.length && vals[i]!= -1){
  26. curr.right = new Node(vals[i]);
  27. q.offer(curr.right);
  28. }i++;
  29. }
  30. return root;
  31. }
  32. static int sum(Node root){
  33. if(root == null) return 0;
  34. if(root.left == null && root.right == null) return root.data;
  35.  
  36. return sum(root.left)+sum(root.right);
  37. }
  38. public static void main(String[]args){
  39. Scanner sc = new Scanner(System.in);
  40. int n = sc.nextInt();
  41. int[] arr = new int[n];
  42. for(int i=0; i<n; i++){
  43. arr[i] = sc.nextInt();
  44. }
  45. Node root = buildtree(arr);
  46. System.out.println(sum(root));
  47. }
  48. }
Success #stdin #stdout 0.13s 54368KB
stdin
7
1 2 3 4 5 -1 -1
stdout
12