Note: This article, including the explanations, code samples in Java, and the visual illustration of a binary search tree, was generated by ChatGPT 4.
A binary search tree (BST) is a tree data structure in which each node has at most two children, referred to as the left child and the right child. It has the following properties:
- Left Subtree Property: For any given node, all the elements in its left subtree are less than the node's value.
- Right Subtree Property: For any given node, all the elements in its right subtree are greater than the node's value.
- No Duplicate Nodes: Each node must have a unique value.
Basic Structure of a Binary Search Tree Node
In Java, a BST node can be represented as:
class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } }
Insertion in a Binary Search Tree
The insertion process starts at the root. We compare the value to be inserted with the root; if less, we go to the left child, if greater, we go to the right child. We keep repeating this process recursively until we find an empty spot where we can insert the new value.
Here is a basic implementation:
```
class BinarySearchTree {
Node root;
BinarySearchTree() {
root = null;
}
void insert(int key) {
root = insertRec(root, key);
}
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;
}
}
```
Searching in a Binary Search Tree
To search for a value, we start at the root and compare the value to be searched with the root. If the value is less, we search the left subtree. If greater, we search the right subtree. This is continued until we find the value or reach a leaf node.
Here's a simple search implementation:
```
class BinarySearchTree {
// ... previous code ...
Node search(Node root, int key) {
if (root == null || root.key == key) {
return root;
}
if (root.key key) {
return search(root.left, key);
}
return search(root.right, key);
}
}
```
Visual Representation of a Binary Search Tree
Let's visualize a BST where we have inserted the following sequence of numbers: 50, 30, 20, 40, 70, 60, 80
.
I'll create an image to illustrate this:
- The root node is
50
. - To the left of
50
, there is a node30
, and to the right, there is70
. 30
has children20
and40
to its left and right respectively.- Similarly,
70
has60
and80
as its left and right children.
Let's generate an image for this tree structure.