Embed
Email

Insert

Document Sample

Categories
Tags
Stats
views:
0
posted:
11/2/2011
language:
English
pages:
3
Insert a node to a tree:

1. Check whether the node exists or not.

2. If not, then attach it to the right place.

i.e., search the right place first, then attach it.

Example:



36







23 47





19 30 42 49





11

22 63

43

38

7

21



2





1. Insert 43 to the above tree.

y x

NIL 36 root

36 47 43>36, right child

47 42 43 42, No right child





Parent of stop

new node

2. Insert 38 to the above tree.

y x

NIL 36 root

36 47 38>36, right child

47 42 38 42, No left child



Parent of

new node stop



3. Insert 30 to the above tree.

y x

NIL 36 root

36 23 3023, No right child



Parent of

new node stop



TREE-INSERT(T, z)

{

y = NIL;

x = root[T];

while(x NIL)

{

y = x;

if(key[z]
x = left[x];

else

x = right[x];

} if T is an empty tree.

Parent[z] = y;

if( y = NIL)

root[T] = z;

else if (key[z] < key[x])

left[y] = z; Attach

else

right[y] = z;

}

Time depends on:

 Where the node is going to insert in.

 How large is the tree.



Time = O(h) = O(height of tree) = O(log(n)) for average case

= O(n) for worst case

= O(1) for best case







O(1)









O(n)





Note:

If you want to build up a Binary Search Tree, you can start an

empty tree with one node and gradually insert nodes.



You can try the example with nothing and add the following

nodes one at a time:



36, 47, 23, 19, 22, 11, 49, 42, 63, 7, 2, 21



Related docs
Other docs by Stariya Js @ B...
Info pack - Level 1
Views: 0  |  Downloads: 0
f1098746053
Views: 0  |  Downloads: 0
file_116
Views: 3  |  Downloads: 0
Trade
Views: 0  |  Downloads: 0
McKenzie_Law.April
Views: 0  |  Downloads: 0
110208attachmentEndingtheUseofCoalCampaign
Views: 0  |  Downloads: 0
Titration Curve _CBL_ _AP_
Views: 0  |  Downloads: 0
FSSC cover note
Views: 0  |  Downloads: 0
link_130115
Views: 0  |  Downloads: 0
Index_of_Supplementary_Tables_and_Dataset
Views: 0  |  Downloads: 0
By registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!