Binary search tree

A Binary Search Tree (BST) is a hierarchical data structure used primarily for fast searching, insertion, and deletion of values in a sorted order.

It has the following properties:

Binary Tree Structure:

Each node in a BST has at most two children, commonly referred to as the left child and the right child.

Ordering Property:

All nodes in the left subtree have values less than the node’s value. All nodes in the right subtree have values greater than the node’s value.

This ordering property of BSTs ensures that searching for a specific value can be performed efficiently, typically in O(log n) time complexity for balanced trees and O(n) in the worst-case scenario for unbalanced trees.

Advantages of Binary Search Trees

Binary search trees are a very efficient data structure for searching, insertion, and deletion operations. The time complexity of these operations is logarithmic in the size of the tree. This means that the time it takes to perform these operations grows slowly as the size of the tree increases.

Disadvantages of Binary Search Trees

One disadvantage of binary search trees is that they can be unbalanced. An unbalanced tree can have a much higher time complexity for searching, insertion, and deletion operations. However, there are techniques that can be used to keep a binary search tree balanced, such as red-black trees and AVL trees.

Applications of Binary Search Trees

  • File systems: File systems use binary search trees to organize files and directories.
  • Databases: Databases use binary search trees to index data for efficient searching.
  • Compilers: Compilers use binary search trees to implement symbol tables.
  • Graphics: Graphics libraries use binary search trees to implement spatial partitioning algorithms.

Differences between binary trees and binary search trees

FeatureBinary TreeBinary Search Tree
DefinitionA binary tree is a non-linear data structure in which each node can have zero, one, or two children. The root node is the topmost node of the tree, and each of its children is another node.A binary search tree is a type of binary tree that adheres to a specific ordering property. In a BST, the value of each node must be greater than all of the values in its left subtree and less than all of the values in its right subtree.
OrderingUnorderedOrdered
Search efficiencyRelatively inefficientEfficient
Insertion and deletion efficiencyRelatively inefficientEfficient
Common applicationsRepresenting hierarchical data structures, such as file systems and directory structuresSearching for specific values, maintaining sorted data collections

Time complexity binary trees vs binary search trees vs balanced binary search Tree

OperationBinary TreeBinary Search TreeBalanced Binary Search Tree (AVL/Red-Black Tree)
SearchO(n)O(log n)O(log n)
InsertionO(n)O(log n)O(log n)
DeletionO(n)O(log n)O(log n)