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