fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. public 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 height(Node root){
  33. if(root == null) return -1;
  34. int left = height(root.left);
  35. int right = height(root.right);
  36.  
  37. return 1 + Math.max(left,right);
  38. }
  39. public static void main(String[]args){
  40. Scanner sc = new Scanner(System.in);
  41. int n = sc.nextInt();
  42. int[] arr = new int[n];
  43. for(int i=0; i<n; i++){
  44. arr[i] = sc.nextInt();
  45. }
  46. Node root = BuildTree(arr);
  47.  
  48. System.out.println(height(root));
  49. }
  50. }
Success #stdin #stdout 0.11s 54416KB
stdin
7
1 2 3 4 5 -1 -1
stdout
2