Binary Search Trees
Binary Search Trees
1) If ROOT=NULL then:
Set LOC:=NULL and PAR:=NULL and return
2) If ITEM=INFO[ROOT],then:
Set LOC:=ROOT and PAR:=NULL and return
3) If ITEM<INFO[ROOT],then:
Set PTR:=LEFT[ROOT] and SAVE:=ROOT
Else:
Set PTR:=RIGHT[ROOT] and SAVE:=ROOT
4) Repeat step 5 and 6 while PTR≠NULL
5) If ITEM=INFO[PTR] then:
Set LOC:=PTR and PAR:=SAVE and return
6) If ITEM<INFO[PTR],then:
Set SAVE:=PTR and PTR:=LEFT[PTR]
Else:
Set SAVE:=PTR and PTR:=RIGHT[PTR]
7) Set LOC:=NULL and PAR:=SAVE
8) Exit
BST(Insertion)
INSBST (INFO, LEFT, RIGHT, ROOT, AVAIL, ITEM, LOC)
1) Call FIND(INFO,LEFT,RIGHT,ROOT,ITEM,LOC,PAR)
2) If LOC != NULL, then Exit
3) a) if 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
4) If PAR=NULL then:
Set ROOT:=NEW
else if: ITEM<INFO[PAR] then:
Set LEFT[PAR]:=NEW
else :
Set RIGHT[PAR]:=NEW
5) exit
BST (Deletion)
CaseA (Info, Left, Right, Root, Loc, Par)
This procedure deletes node N at location Loc, where N doesn’t have 2 children.
Par=Null N is root node; Child=Null N has no child
1) [Initilizes Child]
If Left[Loc]= Null and Right[Loc] = Null, then
Set Child = Null
Else if Left[Loc] ≠ Null, then
Set Child = Left[Loc]
Else
Set Child = Right[Loc]
2) If Par ≠ Null, then
If Loc = Left[Par], then Set Left[Par] = Child
Else Set Right[Par] = Child
Else Set Root = Child
3) Return
BST (Deletion)
CaseB(Info, Left, Right, Root, Loc, Par)
This procedure deletes node N at location Loc, where N has 2 children. Par=Null N
is root node; Suc inorder successor, ParSuc Parent of inorder successor
1) [Find Suc and ParSuc]
a) Set Ptr = Right[Loc] and Save = Loc
b) Repeat while Left[Ptr] ≠ Null
Set Save = Ptr and Ptr = Left[Ptr]
c) Set Suc = Ptr and ParSuc = Save
2) [Delete inorder successor using Procedure of CaseA]
Call CaseA (Info, Left, Right, Root, Suc, ParSuc)
3) [Replace Node N by its inorder successor]
a) If Par ≠ Null, then
If Loc = Left[Par], then Set Left[Par] = Suc
Else Set Right[Par] = Suc
Else Set Root = Suc
b) Set Left[Suc] = Left[Loc] and Right[Suc] = Right[Loc]
4) Return