Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class FindTheNum { //copied
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int n = scan.nextInt();
- int p = scan.nextInt();
- BinarySearchTree<Integer> tree = new BinarySearchTree<>();
- for (int i=0; i<n; ++i)
- tree.insert(scan.nextInt());
- System.out.println(tree.pThNode(p,1)-1000);
- }
- }
- class BinarySearchTree<E extends Comparable<E>> {
- private BNode<E> root;
- public BinarySearchTree() {
- root = null;
- }
- public int pThNode(int p,int counter ) {
- // TODO Auto-generated method stub
- return pThNode(root,p,counter );
- }
- public int pThNode(BNode<E> node, int p,int counter ){
- // System.out.println( );
- if(p==1) {
- return (Integer)node.info;
- }
- else if(counter==p) {
- return (Integer)node.info+1000;
- }
- else {
- counter+=1;
- // System.out.println( );
- if(node.left!=null&&counter<=p)
- counter = pThNode(node.left,p,counter);
- if(node.right!=null&&counter<=p)
- counter = pThNode(node.right,p,counter );
- }
- return counter;
- }
- public void insert(E x) {
- root = insert(x, root);
- }
- private BNode<E> insert(E x, BNode<E> t) {
- if (t == null) {
- t = new BNode<E>(x, null, null);
- } else if (x.compareTo(t.info) < 0) {
- t.left = insert(x, t.left);
- } else if (x.compareTo(t.info) > 0) {
- t.right = insert(x, t.right);
- } else;
- return t;
- }
- public BNode<E> find(E x) {
- return find(x, root);
- }
- private BNode<E> find(E x, BNode<E> t) {
- if (t == null)
- return null;
- if (x.compareTo(t.info) < 0) {
- return find(x, t.left);
- } else if (x.compareTo(t.info) > 0) {
- return find(x, t.right);
- } else {
- return t;
- }
- }
- public boolean isEmpty() {
- return root == null;
- }
- public void printTree() {
- if(isEmpty())
- System.out.println("Empty Tree");
- else {
- printTree(root);
- }
- }
- public void printTree(BNode<E> node) {
- if(node.left!=null) {
- printTree(node.left);
- }
- System.out.println(node.info);
- if(node.right!=null) {
- printTree(node.right);
- }
- }
- }
- class BNode<E extends Comparable<E>> {
- public E info;
- public BNode<E> left;
- public BNode<E> right;
- public BNode(E info) {
- this.info = info;
- left = null;
- right = null;
- }
- public BNode(E info, BNode<E> left, BNode<E> right) {
- this.info = info;
- this.left = left;
- this.right = right;
- }
- }
Add Comment
Please, Sign In to add comment