Advertisement
mantha_raghava

Untitled

May 5th, 2024
1,183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | Source Code | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Solution {
  5.     static class Node{
  6.         int data;
  7.         Node left,right;
  8.         Node(int data){
  9.             this.data=data;
  10.             this.left=null;
  11.             this.right=null;
  12.         }
  13.     }
  14.     public static Node bst(int arr[],Node root,int n){
  15.         for(int i=1;i<n;i++){
  16.             root=insert(root,arr[i]);
  17.         }
  18.         return root;
  19.     }
  20.     public static Node insert(Node root,int val){
  21.         if(root==null){
  22.             return new Node(val);
  23.         }
  24.         if(val<root.data){
  25.             root.left=insert(root.left,val);
  26.         }
  27.         else{
  28.             root.right=insert(root.right,val);
  29.         }
  30.         return root;
  31.     }
  32.     public static int find(Node root,int val,int d){
  33.         if(root==null){
  34.             return -1;
  35.         }
  36.         if(root.data==val){
  37.             return d;
  38.         }
  39.         else if(root.data>val){
  40.             return find(root.left,val,d+=1);
  41.         }
  42.         else{
  43.             return find(root.right,val,d+=1);
  44.         }      
  45.     }
  46.  
  47.     public static void main(String[] args) {
  48.         /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
  49.         Scanner sc=new Scanner(System.in);
  50.         int t=sc.nextInt();
  51.         while(t-->0){
  52.             int n=sc.nextInt();
  53.             int[] arr=new int[n];
  54.             for(int i=0;i<n;i++){
  55.                 arr[i]=sc.nextInt();
  56.             }
  57.             Node rt=new Node(arr[0]);
  58.             Node root=bst(arr,rt,n);
  59.             for(int i=0;i<n;i++){
  60.                 System.out.print(find(root,arr[i],0)+" ");
  61.             }
  62.             System.out.println();
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement