3.8.4.1 Binary Search Tree

Knowledge Base > Algorithm > Data Structure


Overview

Binary Search Tree is a binary tree data structure whose left subtree of a node contains only values less than the value of the node, and right subtree of a node contains only values greater than or equal to the value of the node.

Basic Operation

Algorithm

Pseudocode

Tree-Successor(x)
1 if right[x]nil

2    then return Tree-Minimum(right[x])

3 y p[x]

4 while ynil and x = right[y]

5 do x y

6       y p[y]

7 return y

Tree-Predecessor(x)
1 if left[x]nil

2    then return Tree-Maximum(left[x])

3 y p[x]

4 while ynil and x = left[y]

5 do x y

6       y p[y]

7 return y

Tree-Insert(T,z)
 
1 y nil

2 x root[T]

3 while xnil

4 do y x

5       if key[z] < key[x]

6          then x left[x]

7          else x right[x]

8 p[z] y

9 if y = nil

10    then root[T] z   Tree T was empty

11    else if key[z] <  idkey[y]

12          then left[y] getsz

13          else right[y] z

Tree-Delete(T,z)
 
1 if left[z] = nil or right[z] = nil

2    then y z

3    else y Tree-Successor(z)

4 if left[y]nil

5    then x left[y]

6    else x right[y]

7 if xnil

8    then p[x] p[y]

9 if p[y] = nil

10    then root[T] x

11    else if y = left[p[y]]

12          then left[p[y]] x

13          else right[p[y]] x

14 if yz

15    then key[z] key[y]

16       copy y’s satellite data into z

17 return y

Source Code

Here is the BST implementation, written in C:

Related Topics