You are on page 1of 20

Binary Search Trees

Made By : Pulkit Aggarwal 755/IT/12

A Binary Search Tree is a binary tree with the following properties:


All items in the left sub tree are less than the root. All items in the right sub tree are greater or equal to the root. Each sub tree is itself a binary search tree.

Basic Property
In a binary search tree, the left sub tree contains key values less than the root the right sub tree contains key values greater than or equal to the root.

Operations
Main Operations : Traversal Searching Insertion Deletion Auxiliary Operations : Finding Kth smallest element Sorting

Traversals
Inorder Traversal Preorder Traversal Postorder Traversal

Preorder Traversal

Preorder Traversal: 23 18 12 20 44 35 52 Time Complexity : O(n) Space Complexity : O(n)


8

Postorder Traversal

Postorder Traversal : 12 20 18 35 52 44 23

Time Complexity : O(n)


Space Complexity : O(n)
9

Inorder Traversal

Inorder Traversal : 12 18 20 23 35 44 52 Time Complexity : O(n) Space Complexity : O(n) Inorder traversal of a binary search tree produces a sequenced list.

10

Searching

Time Complexity : O(n)

Space Complexity : O(n) for Stack

11

Insertion

To insert data all we need to do is follow the branches to an empty sub tree and then insert the new node. In other words, all inserts take place at a leaf or at a leaf like node a node that has only one null sub tree.

12

13

14

Deletion

There are the following possible cases when we delete a node: The node to be deleted has no children. In this case, all we need to do is delete the node. The node to be deleted has only a right sub tree. We delete the node and attach the right sub tree to the deleted nodes parent. The node to be deleted has only a left sub tree. We delete the node and attach the left sub tree to the deleted nodes parent. The node to be deleted has two sub trees. It is possible to delete a node from the middle of a tree, but the result tends to create very unbalanced trees.
15

Deletion from the middle of a tree


Rather than simply delete the node, we try to maintain the existing structure as much as possible by finding data to take the place of the deleted data. This can be done in one of two ways : o We can find the largest node in the deleted nodes left sub tree and move its data to replace the deleted nodes data. o We can find the smallest node on the deleted nodes right sub tree and move its data to replace the deleted nodes data.
16

17

18

19

Applications

Used in many search applications where data is constantly entering/leaving, such as the map and set objects in many languages' libraries. Searching in logn time in average case in an unsorted list.

20

You might also like