Sie sind auf Seite 1von 9

Data Structures

Binary Search Tree


Binary Search Trees
 Introduction
 Searching and Insertion
 Deletion
Introduction
Definition :

The value at a node is greater than every value in the left


subtree of the node and is less than every value in the
right subtree of the node.

Node
Value at node > Value of left subtree

Value at node < Value of right subtree


Left Right
Example of a Binary Tree :

38

16 59

9 25 45
83

18 75
Searching and Insertion
Value to be searched = 20

38

14
56

8 23
45 82

18

70
20
Algorithm for searching an element
FIND(INFO, LEFT, RIGHT, ROOT, ITEM, LOC, PAR)
2. [Tree empty ?]
If ROOT=NULL, then: set LOC=NULL and PAR=NULL,
and Return
2. [ITEM at ROOT]
If ITEM=INFO[ROOT], then set LOC=ROOT and PAR=NULL
and Return
8. [Initialize pointers PTR and SAVE.]
If ITEM<INFO[ROOT], then :
Set PTR=LEFT[ROOT] and SAVE=ROOT.
Else
Set PTR=RIGHT{ROOT] and SAVE=ROOT.
[End of if Structure]
14.Repeat Steps 5 and 6 while PTR ╪ NULL
15. [ITEM Found?]
If ITEM=INFO[PTR], then Set LOC=PTR and
PAR=SAVE, and Return.

Contd…
Algorithm for searching an element

6. If ITEM<INFO[PTR], then:
set SAVE=PTR and PTR=LEFT[PTR]
Else:
set SAVE=PTR and PTR=RIGHT[PTR].
[End of if structure]
[End of Step 4 loop]
7. [Search Unsuccessful.] Set LOC=NULL AND PAR=SAVE
8. Exit.
Algorithm for insertion of an element

INSBST(INFO,LEFT,RIGHT,ROOT,ITEM,LOC,PAR)
2. Call FIND(INFO,LEFT,RIGHT,ROOT,ITEM,LOC,PAR)
3. If LOC╪NULL, then EXIT
4. [COPY ITEM into new node in AVAIL list.]
(A) AVAIL=NULL then Write OVERFLOW, and EXIT.
(B) Set NEW=AVAIL, AVAIL=LEFT[AVAIL] and INFO[NEW]=ITEM
(C) Set LOC=NEW, LEFT[NEW]=NULL and RIGHT[NEW]=NULL.
8. [Add ITEM to Tree]
If PAR = NULL, THEN:
set ROOT=NEW.
Else If ITEM<INFO[PAR], then:
set LEFT[PAR]=NEW.
Else
set RIGHT[PAR]=NEW
[End of IF structure]
5. EXIT.
Deletion of element
 Root node N has no child nodes
 N has exactly one child node either in left or in the
right
 N has child nodes on both the sides

Das könnte Ihnen auch gefallen