0% found this document useful (0 votes)
7 views

lab04

Uploaded by

ayaanmemon1807s
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)
7 views

lab04

Uploaded by

ayaanmemon1807s
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/ 3

class Node {

int value;

Node left, right;

public Node(int value) {

this.value = value;

left = right = null;

public class BinarySearchTree {

Node root;

public BinarySearchTree() {

root = null;

// Insert a value into the BST

public void insert(int value) {

root = insertRec(root, value);

private Node insertRec(Node root, int value) {

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

// In-order Traversal
public void inOrder() {
inOrderRec(root);
System.out.println();
}

private void inOrderRec(Node root) {


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

// Pre-order Traversal
public void preOrder() {
preOrderRec(root);
System.out.println();
}

private void preOrderRec(Node root) {


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

// Post-order Traversal
public void postOrder() {
postOrderRec(root);
System.out.println();
}

private void postOrderRec(Node root) {


if (root != null) {
postOrderRec(root.left);
postOrderRec(root.right);
System.out.print(root.value + " ");
}}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
int[] values = {50, 30, 20, 40, 70, 60, 80};

// Insert values into BST


for (int value : values) {
bst.insert(value);
}

// Display traversals
System.out.println("In-order Traversal:");
bst.inOrder();

System.out.println("Pre-order Traversal:");
bst.preOrder();

System.out.println("Post-order Traversal:");
bst.postOrder();
}
}

You might also like