What is a Binary Tree

A Binary Tree is a non-linear data structure (meaning you do not have to define its size at run time). Linked List it takes time to traverse it when searching for a value. In a binary tree the data is split, smaller values on the left, larger values on the right.

Pre Order, in order, post order traversal

Pre Order: root, left, right

In Order: left, root, right

Post Order: left, right, root

Trees

Binary Search Tree

Binary Search Tree

A Binary Search Tree (BST) is a hierarchical data structure with the following properties:

This structure allows for efficient searching, insertion, and deletion operations, typically with an average time complexity of O(log n) in balanced trees.

Traversal of a binary tree

  1. Pre Order: Root, Left, Right (8,3,1,6,4,7,10,14,13)
  2. Inorder: Left, Root, Right (1,3,4,6,7,8,10,13,14)
  3. Post Order: Left, Right, Root (1,4,7,6,3,13,14,10,8)

Nomenclature

Time Complexity

Searching

  • Average Case: O(log n)

  • Worst Case: O(n)

Searching in a BST typically involves traversing from the root to a leaf, comparing the target value with each node. In a balanced tree, this process eliminates half the remaining nodes at each step, resulting in O(log n) complexity. However, in an unbalanced tree that degenerates into a linked list, the worst-case time complexity becomes O(n)

Insertion

  • Average Case: O(log n)

  • Worst Case: O(n)

Insertion follows a similar path to searching, as it needs to find the correct position to place the new node. In a balanced tree, this operation takes O(log n) time on average. However, if the tree becomes unbalanced due to the order of insertions, the worst-case time complexity can degrade to O(n).

Deletion

Deletion is slightly more complex but generally has the same time complexity as insertion and searching. The process involves finding the node to delete (O(log n) in balanced trees) and then handling three possible cases

  1. Deleting a leaf node

  2. Deleting a ndoe with one child

  3. Deleting a node with two children

The third case is the most complex, often involving finding the in-order successor or predecessor. Despite this, the overall time complexity remains O(log n) for balanced trees and O(n) in the worst case for unbalanced trees.

It's important to note that these time complexities assume a basic, unbalanced BST. Self-balancing BSTs like AVL trees or Red-Black trees maintain balance through rotations, ensuring O(log n) worst-case time complexity for all operations.