Skip to content

Commit dfd84f4

Browse files
authored
Binary Search Tree in java
1 parent edd69bd commit dfd84f4

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
class Node {
8+
int data;
9+
Node left, right;
10+
Node(int x)
11+
{
12+
data = x;
13+
left = right = null;
14+
}
15+
}
16+
17+
public class BinaryTree {
18+
19+
static int count = 0;
20+
public static Node insert(Node root, int x)
21+
{
22+
if (root == null)
23+
return new Node(x);
24+
if (x < root.data)
25+
root.left = insert(root.left, x);
26+
else if (x > root.data)
27+
root.right = insert(root.right, x);
28+
return root;
29+
}
30+
31+
public static Node kthSmallest(Node root, int k)
32+
{
33+
if (root == null)
34+
return null;
35+
Node left = kthSmallest(root.left, k);
36+
37+
if (left != null)
38+
return left;
39+
count++;
40+
if (count == k)
41+
return root;
42+
43+
return kthSmallest(root.right, k);
44+
}
45+
46+
public static void printKthSmallest(Node root, int k)
47+
{
48+
count = 0;
49+
50+
Node res = kthSmallest(root, k);
51+
if (res == null)
52+
System.out.println("can't print as k is greater than nodes");
53+
else
54+
System.out.println(k+"-th Smallest Element is " + res.data);
55+
}
56+
57+
public static void main (String[] args) {
58+
Scanner take = new Scanner(System.in);
59+
Node root = null;
60+
System.out.print("enter number of elements in the list: ");
61+
int size = take.nextInt();
62+
63+
while(size-- !=0)
64+
root = insert(root, take.nextInt());
65+
System.out.print("enter k: ");
66+
int k = take.nextInt();
67+
printKthSmallest(root, k);
68+
69+
70+
}
71+
}

0 commit comments

Comments
 (0)