Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Rooted and Binary Tree
A rooted tree G is a connected acyclic graph with a special node called the root, from which every edge directly or indirectly originates. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered.
- If every internal vertex has not more than m children, it is called an m-ary tree.
- If every internal vertex has exactly m children, it is called a full m-ary tree.
- If m = 2, the rooted tree is called a binary tree.
Binary Search Tree
A Binary Search Tree (BST) is a binary tree that satisfies the following property −
- For any vertex V, all vertices X in the left sub-tree have Value(X) ≤ Value(V).
- For any vertex V, all vertices Y in the right sub-tree have Value(Y) ≥ Value(V).
The height of a BST is the number of edges from the root to the deepest node.
Example
In the BST above, the root is 25. All values in the left subtree (10, 15, 20) are ≤ 25, and all values in the right subtree (30, 35, 40) are ≥ 25. This property holds recursively at every node.
Algorithm to Search for a Key in BST
The following pseudocode searches for a key k in a BST rooted at node x −
BST_Search(x, k)
if (x = NIL or k = Value[x])
return x
if (k < Value[x])
return BST_Search(left[x], k)
else
return BST_Search(right[x], k)
The algorithm starts at the root and compares the key with the current node's value. If the key is smaller, it goes left; if larger, it goes right. This continues until the key is found or a NIL node is reached.
Complexity of Binary Search Tree
| Operation | Average Case | Worst Case |
|---|---|---|
| Space | O(n) | O(n) |
| Search | O(log n) | O(n) |
| Insertion | O(log n) | O(n) |
| Deletion | O(log n) | O(n) |
The worst case O(n) occurs when the BST becomes a skewed tree (essentially a linked list), where every node has only one child. The average case O(log n) occurs when the tree is balanced.
Conclusion
A rooted tree has a designated root vertex, and a binary tree limits each node to at most two children. A Binary Search Tree maintains a sorted order property that enables efficient O(log n) average-case search, insertion, and deletion operations.
