0% found this document useful (0 votes)
6 views5 pages

Project of DSA

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Project of DSA

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Project of DSA

Group members:
Alishba Nadeem
BSAI-168
Ilsa javed
BSAI-200
Dure Adan Noor
BSAI-211
Presented to:
Ma’am Iqra
Question:

We had made a Java program to implement a Binary Search Tree (BST)


that supports the following operations:

1. Insertion – Add new keys to the BST.


2. Search – Check if a specific key exists in the BST.
3. In-order Traversal – Print all the keys in ascending order.

class BinarySearchTree {
class Node {
int key;
Node left, right;

Node(int key) {
this.key = key;
left = right = null;
}
}

private Node root;

public void insert(int key) {


root = insertRec(root, key);
}

private Node insertRec(Node root, int key) {

if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);

return root;
}

public boolean search(int key) {


return searchRec(root, key);
}

private boolean searchRec(Node root, int key) {

if (root == null)
return false;
if (root.key == key)
return true;

return key < root.key ? searchRec(root.left, key) : searchRec(root.right, key);


}
public void inorder() {
inorderRec(root);
System.out.println(); // Print a newline after traversal
}

private void inorderRec(Node root) {


if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}

public static void main(String[] args) {


System.out.println("=== Binary Search Tree Project ===\n");

BinarySearchTree bst = new BinarySearchTree();

System.out.println("Inserting keys into the BST...");


bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);

System.out.println("\nIn-order Traversal:");
bst.inorder();

System.out.println("Searching keys in the BST:");


System.out.println("Is 40 in the BST? " + bst.search(40)); // true
System.out.println("Is 90 in the BST? " + bst.search(90)); // false
}
}

Output:

You might also like