Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Solution {
- static class Node{
- int data;
- Node left,right;
- Node(int data){
- this.data=data;
- this.left=null;
- this.right=null;
- }
- }
- public static Node bst(int arr[],Node root,int n){
- for(int i=1;i<n;i++){
- root=insert(root,arr[i]);
- }
- return root;
- }
- public static Node insert(Node root,int val){
- if(root==null){
- return new Node(val);
- }
- if(val<root.data){
- root.left=insert(root.left,val);
- }
- else{
- root.right=insert(root.right,val);
- }
- return root;
- }
- public static int find(Node root,int val,int d){
- if(root==null){
- return -1;
- }
- if(root.data==val){
- return d;
- }
- else if(root.data>val){
- return find(root.left,val,d+=1);
- }
- else{
- return find(root.right,val,d+=1);
- }
- }
- public static void main(String[] args) {
- /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
- Scanner sc=new Scanner(System.in);
- int t=sc.nextInt();
- while(t-->0){
- int n=sc.nextInt();
- int[] arr=new int[n];
- for(int i=0;i<n;i++){
- arr[i]=sc.nextInt();
- }
- Node rt=new Node(arr[0]);
- Node root=bst(arr,rt,n);
- for(int i=0;i<n;i++){
- System.out.print(find(root,arr[i],0)+" ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement