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 find(Node root){
  33. if(root == null) return 0;
  34. if(root.left!=null && root.right!=null) return 1;
  35. // if(root.left==null && root.right!=null) return 1;
  36.  
  37. int count = find(root.left)+find(root.right);
  38.  
  39. return count;
  40. }
  41. public static void main(String[]args){
  42. Scanner sc = new Scanner(System.in);
  43. int n = sc.nextInt();
  44. int[] arr = new int[n];
  45. for(int i=0; i<n; i++){
  46. arr[i] = sc.nextInt();
  47. }
  48. Node root = buildtree(arr);
  49. System.out.println(find(root));
  50. }
  51. }
Success #stdin #stdout 0.14s 56528KB
stdin
7
1 2 3 4 5 -1 -1
stdout
1