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

BST Example

The document outlines a simple implementation of a Binary Search Tree (BST) in Java, including methods for inserting nodes, searching for values, and performing an inorder traversal. It features a Node class to represent each element in the tree and includes recursive functions for both insertion and searching. The main method demonstrates the functionality by inserting values and performing searches.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

BST Example

The document outlines a simple implementation of a Binary Search Tree (BST) in Java, including methods for inserting nodes, searching for values, and performing an inorder traversal. It features a Node class to represent each element in the tree and includes recursive functions for both insertion and searching. The main method demonstrates the functionality by inserting values and performing searches.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

class BinarySearchTree { }

class Node { // Search for a value in the BST


int data; public boolean search(int data) {
Node left, right; return searchRec(root, data);
}
public Node(int data) {
this.data = data; // Recursive search function
left = right = null; private boolean searchRec(Node root, int data) {
} if (root == null) {
} return false;
}
private Node root;
if (data == root.data) {
public BinarySearchTree() { return true;
root = null; }
}
if (data < root.data) {
// Insert a node into the BST return searchRec(root.left, data);
public void insert(int data) { }
root = insertRec(root, data);
} return searchRec(root.right, data);
}
// Recursive insert function
private Node insertRec(Node root, int data) { // Main method to test the BinarySearchTree class
if (root == null) { public static void main(String[] args) {
root = new Node(data); BinarySearchTree bst = new BinarySearchTree();
return root;
} // Insert values into the BST
bst.insert(50);
if (data < root.data) { bst.insert(30);
root.left = insertRec(root.left, data); bst.insert(20);
} else if (data > root.data) { bst.insert(40);
root.right = insertRec(root.right, data); bst.insert(70);
} bst.insert(60);
bst.insert(80);
return root;
} // Print the inorder traversal (sorted order)
System.out.println("Inorder traversal:");
// Inorder Traversal (Left, Root, Right) bst.inorder();
public void inorder() {
inorderRec(root); // Search for a value in the BST
} System.out.println("\nSearch 40: " +
bst.search(40));
// Recursive inorder traversal System.out.println("Search 25: " + bst.search(25));
private void inorderRec(Node root) { }
if (root != null) { }
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}

You might also like