Advertisement
unknown_0711

Untitled

Nov 29th, 2022
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1.  
  2.  
  3.  
  4. import java.util.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. public class Main
  9. {
  10. static int ans = 1, index=0;
  11. public static class Node{
  12. int val;
  13. Node left;
  14. Node right;
  15. Node(int val) {
  16. this.val = val;
  17. this.left = null;
  18. this.right = null;
  19. }
  20. }
  21.  
  22. public static Node insert(Node root, int val){
  23. if(root == null) {
  24. return new Node(val);
  25. }
  26.  
  27. if(val < root.val){
  28. root.left = insert(root.left, val);
  29. }
  30. else
  31. root.right = insert(root.right, val);
  32.  
  33. return root;
  34. }
  35.  
  36. public static void inOrderTraversal(Node root , int[] arr){
  37. if(root == null) {
  38. return;
  39. }
  40.  
  41. inOrderTraversal(root.left, arr);
  42.  
  43. if(root.val != arr[index]){
  44. ans = 0;
  45. }
  46. index+=1;
  47. inOrderTraversal(root.right, arr);
  48.  
  49. }
  50. public static void main (String[] args) throws java.lang.Exception
  51. {
  52. Scanner in = new Scanner(System.in);
  53. int size = in.nextInt();
  54.  
  55. int arr[] = new int[size];
  56.  
  57. for(int i = 0; i < size; i++) {
  58. arr[i] = in.nextInt();
  59. }
  60.  
  61. Node root = null;
  62. root = new Node(arr[0]);
  63.  
  64. for(int i = 1; i < size; i++) {
  65. root = insert(root, arr[i]);
  66. }
  67.  
  68. inOrderTraversal(root, arr);
  69.  
  70. System.out.print(ans);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement