Lab 10
Lab 10
Objective:
Theory:
A Binary Search Tree (BST) is a binary tree in which each node has a key greater than all the
keys in its left subtree and smaller than all the keys in its right subtree.
Tree traversal refers to visiting all the nodes in a tree in a specific order:
Tasks:
Algorithm:
2. Traversals:
• In-order Traversal:
1. Traverse the left subtree.
2. Visit the root node.
3. Traverse the right subtree.
• Pre-order Traversal:
1. Visit the root node.
2. Traverse the left subtree.
3. Traverse the right subtree.
• Post-order Traversal:
1. Traverse the left subtree.
2. Traverse the right subtree.
3. Visit the root node.
class Node {
int key;
Node left, right;
class BinarySearchTree {
Node root;
BinarySearchTree() {
root = null;
}
// Insert method
void insert(int key) {
root = insertRec(root, key);
}
// In-order traversal
void inorder() {
inorderRec(root);
}
// Pre-order traversal
void preorder() {
preorderRec(root);
}
// Post-order traversal
void postorder() {
postorderRec(root);
}
System.out.println("In-order Traversal:");
tree.inorder();
System.out.println("\nPre-order Traversal:");
tree.preorder();
System.out.println("\nPost-order Traversal:");
tree.postorder();
}
}
Lab Task:
1. Create a binary search tree of student marks and perform above types of traversals on it.