next next up down toc toc mail

7.13.  Inserting an Element in a BST

Adding a new element x to a BST is straightforward. The following recursive algorithm sketches the idea:

Basis: If the tree is empty, replace T by a new node and place x at that node. If the tree is not empty and its root has element x, then x is already in the tree and we do nothing.

Induction: If the tree is not empty and does not have x at its root, then insert x into the left subtree if x is less than the element at the root, or insert x into the right subtree if x is greater than the element at the root.

The algorithm as a Nassi Shneidermann diagram:

Procedure Insert_Element(node new_root, lable x):

[picture]

Examples:


back next up down toc toc mail


Created by unroff & hp-tools. © by Hans-Peter Bischof. All Rights Reserved (1998).

Last modified: 27/July/98 (12:14)