Skip to content

Commit 1941dcd

Browse files
Merge pull request #45 from mahesh-11102/master
Binary Search Tree in java
2 parents d02c7fb + 56cb1d9 commit 1941dcd

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Question:
2+
// Write a Java program to identify the kth smallest element in the binary search tree where k =8.
3+
4+
import java.util.*;
5+
import java.io.*;
6+
7+
// initializing node class
8+
class Node {
9+
int data;
10+
Node left, right;
11+
Node(int x) // Node contructor
12+
{
13+
data = x;
14+
left = right = null;
15+
}
16+
}
17+
18+
public class BinaryTree {
19+
20+
static int count = 0;
21+
// insertion of element using recursion
22+
public static Node insert(Node root, int data)
23+
{
24+
if (root == null)
25+
return new Node(data);
26+
if (data < root.data) // if the data is less than node data go left
27+
root.left = insert(root.left, data);
28+
29+
else if (data > root.data) // if data is greater than node data go right
30+
root.right = insert(root.right, data);
31+
32+
return root;
33+
}
34+
35+
public static Node kthSmallest(Node root, int k)
36+
{
37+
if (root == null)
38+
return null;
39+
Node left = kthSmallest(root.left, k); // at this line we go to leftmost node, so that we can start counting nth smallest from thatnode (leftmost)
40+
41+
if (left != null)
42+
return left;
43+
count++;
44+
45+
if (count == k) // if we find the element at k return k;
46+
return root;
47+
48+
return kthSmallest(root.right, k);
49+
}
50+
51+
public static void printKthSmallest(Node root, int k)
52+
{
53+
count = 0;
54+
Node res = kthSmallest(root, k); // get the smallest element
55+
56+
if (res == null)
57+
System.out.println("can't print as k is greater than nodes");
58+
else
59+
System.out.println(k+"-th Smallest Element is " + res.data);
60+
}
61+
62+
public static void main (String[] args) {
63+
Scanner take = new Scanner(System.in);
64+
Node root = null; // initialising root node
65+
66+
System.out.print("enter number of elements in the list: ");
67+
int size = take.nextInt();
68+
69+
while(size-- !=0)
70+
root = insert(root, take.nextInt()); // calling insert method to insert the element in the tree
71+
System.out.print("enter k: ");
72+
int k = take.nextInt();
73+
printKthSmallest(root, k); //calling this function to find the kth smallest element
74+
75+
76+
}
77+
}

0 commit comments

Comments
 (0)