Professional Documents
Culture Documents
Lecture No. 12
___________________________________________________________________
Data Structures
Lecture No. 12
Reading Material
Data Structures And Algorithm analysis in C++
Chapter 4
4.2, 4.3(4.3.2, 4.3.4)
Summary
Description
Returns a pointer to the left sub-tree
Returns a pointer to the right sub-tree
Returns the father node of p
Returns the brother node of p
Page 1 of 13
These methods have already been discussed at the end of the previous lecture, however,
few more methods are required to construct a binary tree:
Operation
setLeft(p, x)
setRight(p, x)
Description
Creates the left child node of p and set
the value x into it.
Creates the right child node of p, the
child node contains the info x.
All these methods are required to build and to retrieve values from a tree.
1
4
14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5
1
4
Page 3 of 13
14
15
Page 4 of 13
1
4
4
1
5
Fig 12.6: The node is added as the left child of the root node
The next number in the list is 9. To add this number in the tree, we will follow the already
defined and experimented procedure. We compare this number first with the number in
the root node of the tree. This number is found to be smaller than the number in the root
node. Therefore, left sub-tree of the root node is sought. The left child of the root node is
the one with number 4. On comparison, number 9 is found greater than the number 4.
Therefore, we go to the right child of the node with number 4. At the moment, there is no
further node to the right of it, necessitating the need of creating a new node. The number
9 is put into it and the new node is added as the right child of the node with number 4.
The same is shown in the figure given below.
1
4
4
9
1
5
Page 5 of 13
1
4
4
3
9
7
5
1
5
1
8
1
6
2
0
1
7
Trace of insert
We will take the tree and the figure, we constructed above. At this time, we want to insert
some new numbers in the tree as given in the figure below:
p
q
1
1
4
7
4
1
5
3
9
1
8
7
1
2
6
0
17, 9, 14, 5
5
Page 10 of 13
Initially the pointers p and q are pointing to the start (root) of the tree. We want to insert
the number 17 in the tree. We compare the number in the root node (14) with number 17.
Because number 17 is greater than the number 14, so as we did in the while loop in the
function above, we will move toward the right sub-tree. In the next picture below, we can
see that the pointer q has moved to the right sub-tree of the root.
p
1
4
1
7
4
3
1
5
9
7
1
8
1
6
2
0
5
17, 9, 14, 5
1
7
4
3
q
9
1
5
1
6
1
8
2
0
5
17, 9, 14, 5
Page 11 of 13
1
7
4
3
1
5
p
1
8
2
0
1
6
5
17, 9, 14, 5
1
7
4
3
1
5
9
7
5
1
6
1
8
2
0
q
17, 9, 14, 5
1
5
9
7
1
6
5
17, 9, 14, 5
1
8
2
0
node
1
7
p->setRight( node ) ;
Page 13 of 13