drva 6
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = Integer.parseInt(scn.next());
int q = Integer.parseInt(scn.next());
BinarySearchTree<Integer> tree = new BinarySearchTree<>();
HashMap<Integer, BNode<Integer>> map = new HashMap<>();
for(int i = 0; i<q+n; i++){
String command = scn.next();
if(command.equals("insert")){
int num = Integer.parseInt(scn.next());
tree.insert(num);
}
else if(command.equals("ask")){
int node = Integer.parseInt(scn.next());
System.out.println(nodeDepth(node, tree.getRoot(), 1));
}
}
}
public static int nodeDepth(int val, BNode<Integer> node, int depth){
if(node==null) return -1;
if(node.info == val) return depth;
int leftDepth = nodeDepth(val, node.left, depth+1);
if(leftDepth!=-1) return leftDepth;
return nodeDepth(val, node.right, depth+1);
}
}
Editor is loading...
Leave a Comment