Trees-Data-Structure 17
Trees-Data-Structure 17
Trees-Data-Structure 17
Topperworld.in
BINARY TREES
Trees and Graphs are widely used non-linear data structures. Tree and
graph structures represents hierarchial relationship between individual
data elements. Graphs are nothing but trees with certain restrictions
removed.
➔TREES:
a
a
b c b c
d e f d e
©Topperworld
Data Structure and Algorithms
on them are called ordered tree data structures. Ordered trees are by
far the commonest form of tree data structure.
➔BINARY TREE:
In general, tree nodes can have any number of children. In a binary tree,
each node can have at most two children. A binary tree is either empty or
consists of a node called the root together with two binary trees called the
left subtree and the right subtree.
A tree with no nodes is called as a null tree. A binary tree is shown in figure
right subtree
left subtree D E F G
H I
Binary trees are easy to implement because they have a small, fixed
number of child links. Because of this characteristic, binary trees are the
a
a
b c b c
d e f d e
©Topperworld
Data Structure and Algorithms
Tree Terminology:
Leaf node
Path
A sequence of nodes n1, n2, . . ., nk, such that ni is the parent of ni
+ 1 for i = 1, 2,. . ., k - 1. The length of a path is 1 less than the
number of nodes on the path. Thus there is a path of length zero
from a node to itself.
Siblings
For the tree shown in figure, F and G are the siblings of the parent
node C and H and I are the siblings of the parent node D.
Subtree
Level
The level of the node refers to its distance from the root. The root of
the tree has level O, and the level of any other node in the tree is
one more than the level of its parent. For example, in the binary tree
of Figure 5.2.1 node F is at level 2 and node H is at level 3. The
maximum number of nodes at any level is 2n.
©Topperworld
Data Structure and Algorithms
a
a
b c b c
d e f d e
The nodes of a binary tree can be numbered in a natural way, level by level,
left to right. The nodes of a complete binary tree can be numbered so that
the root is assigned the number 1, a left child is assigned twice the number
assigned its parent, and a right child is assigned one more than twice the
number assigned its parent. For example, see Figure .
©Topperworld
Data Structure and Algorithms
3. Since a binary tree can contain at most one node at level 0 (the root),
it can contain at most 2l node at level l.
If every non-leaf node in a binary tree has nonempty left and right
subtrees, the tree is termed as strictly binary tree. Thus the tree of figure
is strictly binary. A strictly binary tree with n leaves always contains 2n - 1
nodes.
A full binary tree of height h has all its leaves at level h. Alternatively; All
non leaf nodes of a full binary tree have two children, and the leaf nodes
have no children.
A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of
height h is a strictly binary tree all of whose leaves are at level h. Figure
5.2.3(d) illustrates the full binary tree containing 15 nodes and of height 3.
A full binary tree of height h contains 2h leaves and, 2h - 1 non-leaf nodes.
h
Thus by induction, total number of nodes (tn) = ∑ 2 l = 2 h+1−1.
l =0
©Topperworld
Data Structure and Algorithms
A complete binary tree of height h looks like a full binary tree down
to level h-1, and the level h is filled from left to right.
A complete binary tree with n leaves that is not strictly binary has
2n nodes. For example, the tree of Figure is a complete binary tree
having 5 leaves and 10 nodes.
1 1 1
2 3 2 3 2
4 5 6 4 5 7 4
Complete Binary Tree Not Complete and not Not Complete and not
but not strict strict strict
(a) (b) (c)
©Topperworld
Data Structure and Algorithms
We define two terms: Internal nodes and external nodes. An internal node
is a tree node having at least one–key and possibly some children. It is
some times convenient to have another types of nodes, called an external
node, and pretend that all null child links point to such a node. An external
node doesn’t exist, but serves as a conceptual place holder for nodes to be
inserted.
We draw internal nodes using circles, with letters as labels. External nodes
are denoted by squares. The square node version is sometimes called an
extended binary tree. A binary tree with n internal nodes has n+1 external
nodes. Figure shows a sample tree illustrating both internal and external
nodes.
a d Internal Nodes: a, b, c, d
External Nodes: 1, 2, 3, 4, 5
1 b 4 5
2 3
Array-based Implementation:
Binary trees can also be stored in arrays, and if the tree is a complete
binary tree, this method wastes no space. In this compact arrangement, if
a node has an index i, its children are found at indices 2i+1 and 2i+2, while
its parent (if any) is found at index floor((i-1)/2) (assuming the root of the
tree stored in the array at an index zero).
This method benefits from more compact storage and better locality of
reference, particularly during a preorder traversal. However, it requires
contiguous memory, expensive to grow and wastes space proportional to
2h - n for a tree of height h with n nodes.
©Topperworld
Data Structure and Algorithms
0 1 2 3 4 5 6
Array representation is good for complete binary tree, but it is wasteful for
many other binary trees. The representation suffers from insertion and
deletion of node from the middle of the tree, as it requires the moment of
potentially many nodes to reflect the change in level number of this node.
To overcome this difficulty we represent the binary tree in linked
representation.
In linked representation each node in a binary has three fields, the left child
field denoted as LeftChild, data field denoted as data and the right child
field denoted as RightChild. If any sub-tree is empty then the
corresponding pointer’s LeftChild and RightChild will store a NULL value.
If the tree itself is empty the root pointer will store a NULL value.
• Memory spaces are wasted for storing NULL pointers for the
nodes, which have no subtrees.
©Topperworld
Data Structure and Algorithms
A root
B C
A
D E F G
B C
H I
D X E X X F X X G X
X H X X I X
1. Preorder
2. Inorder
3. Postorder
4. Level order
In the first three traversal methods, the left subtree of a node is traversed
before the right subtree. The difference among them comes from the
difference in the time at which a root node is visited.
Inorder Traversal:
In the case of inorder traversal, the root of each subtree is visited after its
left subtree has been traversed but before the traversal of its right subtree
begins. The steps for traversing a binary tree in inorder traversal are:
©Topperworld
Data Structure and Algorithms
Preorder Traversal:
In a preorder traversal, each root node is visited before its left and right
subtrees are traversed. Preorder search is also called backtracking. The
steps for traversing a binary tree in preorder traversal are:
©Topperworld
Data Structure and Algorithms
Postorder Traversal:
In a postorder traversal, each root is visited after its left and right subtrees
have been traversed. The steps for traversing a binary tree in postorder
traversal are:
1. Visit the left subtree, using postorder.
2. Visit the right subtree, using postorder
3. Visit the root.
In a level order traversal, the nodes are visited level by level starting from
the root, and going from left to right. The level order traversal requires a
queue data structure. So, it is not possible to develop a recursive procedure
to traverse the binary tree in level order. This is nothing but a breadth first
search technique.
The algorithm for level order traversal is as follows:
void levelorder()
{
int j;
for(j = 0; j < ctr; j++)
{
if(tree[j] != NULL)
print tree[j] -> data;
}
}
©Topperworld
Data Structure and Algorithms
Example 1:
D E F
• Postorder traversal
yields:
G H I D, B, G, E, H, I, F, C, A
Example 2:
Traverse the following binary tree in pre, post, inorder and level order.
W
• Inorder traversal yields:
B, F, G, H, P, R, S, T, W, Y, Z
©Topperworld
Data Structure and Algorithms
Example 3:
Traverse the following binary tree in pre, post, inorder and level order.
2 • Preorder
7 5 traversal yields:
2, 7, 2, 6, 5, 11,
2 6 9 5, 9, 4
5 11 4
• Postorder
travarsal yields:
2, 5, 11, 6, 7, 4,
9, 5, 2
• Inorder
travarsal yields:
2, 7, 5, 6, 11, 2,
5, 4, 9
• Level order
traversal yields: 2,
7, 5, 2, 6, 9, 5, 11, 4
Binary Tree Pre, Post, Inorder and level order Traversing
Example 4:
Traverse the following binary tree in pre, post, inorder and level order.
L M
• Inorder travarsal yields:
K, G, D, L, H, M, B, A, E, C
G
• Level order traversal yields:
K A, B, C, D, E, G, H, K, L, M
Binary Tree Pre, Post, Inorder and level order Traversing
©Topperworld
Data Structure and Algorithms
If the preorder traversal is given, then the first node is the root node. If
the postorder traversal is given then the last node is the root node. Once
the root node is identified, all the nodes in the left sub-trees and right sub-
trees of the root node can be identified using inorder.
It can be noted that, for the purpose mentioned, two traversal are essential
out of which one should be inorder traversal and another preorder or
postorder; alternatively, given preorder and postorder traversals, binary
tree cannot be obtained uniquely.
Example 1:
Preorder: A B D G C E H I F
Inorder: D G B A H E I C F
Solution:
©Topperworld
Data Structure and Algorithms
DGB HEICF
From the inorder sequence D G B, we can find that D and G are to the left
of B.
B HEICF
DG
From the inorder sequence D G, we can find that there is no left node to D
and G is at the right of D.
B HEICF
©Topperworld
Data Structure and Algorithms
From the preorder sequence C E H I F, the root of the left sub tree
is: C
From the inorder sequence H E I C F, we can find that H E I are at the left
of C and F is at the right of C.
B C
D HEI F
From the inorder sequence H E I, we can find that H is at the left of E and
I is at the right of E.
B C
D E F
G H I
Example 2:
Inorder: D G B A H E I C F
Postorder: G D B H I E F C A
Solution:
©Topperworld
Data Structure and Algorithms
DGB HEICF
From the inorder sequence D G B, we can find that D G are to the left of B
and there is no right subtree for B.
B HEICF
DG
From the inorder sequence D G, we can find that is no left subtree for D
and G is to the right of D.
B HEICF
©Topperworld
Data Structure and Algorithms
From the postorder sequence H I E F C, the root of the left sub tree
is: C
From the inorder sequence H E I C F, we can find that H E I are to the left
of C and F is the right subtree for C.
The Binary tree upto this point looks like:
A
B C
D HEI F
From the inorder sequence H E I, we can find that H is left subtree for E
and I is to the right of E.
B C
D E F
G H I
Example 3:
Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Preorder: n6 n2 n1 n4 n3 n5 n9 n7 n8
Solution:
From Preorder sequence n6 n2 n1 n4 n3 n5 n9 n7 n8, the root is:
n6
©Topperworld
Data Structure and Algorithms
n1 n2 n3 n4 n5 n7 n8 n9
To find the root, left and right sub trees for n1 n2 n3 n4 n5:
n2 n7 n8 n9
n1 n3 n4 n5
To find the root, left and right sub trees for n3 n4 n5:
From the preorder sequence n4 n3 n5, the root of the tree is: n4
From the inorder sequence n3 n4 n5, we can find that n3 is to the left of
n4 and n5 is at the right of n4.
n2 n7 n8 n9
n1 n4
n3 n5
©Topperworld
Data Structure and Algorithms
To find the root, left and right sub trees for n7 n8 n9:
From the preorder sequence n9 n7 n8, the root of the left sub tree
is: n9
From the inorder sequence n7 n8 n9, we can find that n7 and n8 are at
the left of n9 and no right subtree of n9.
n9
n2
n1 n4 n7 n8
n3 n5
To find the root, left and right sub trees for n7 n8:
From the preorder sequence n7 n8, the root of the tree is: n7
From the inorder sequence n7 n8, we can find that is no left subtree for
n7 and n8 is at the right of n7.
n9
n2
n1 n4 n7
n3 n5 n8
Example 4:
Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9
Postorder: n1 n3 n5 n4 n2 n8 n7 n9 n6
©Topperworld
Data Structure and Algorithms
Solution:
n6
n1 n2 n3 n4 n5 n7 n8 n9
To find the root, left and right sub trees for n1 n2 n3 n4 n5:
n6
n2 n7 n8 n9
n1 n3 n4 n5
To find the root, left and right sub trees for n3 n4 n5:
From the postorder sequence n3 n5 n4, the root of the tree is: n4
From the inorder sequence n3 n4 n5, we can find that n3 is to the left of
n4 and n5 is to the right of n4. The Binary tree upto this point looks like:
©Topperworld
Data Structure and Algorithms
n6
n2 n7 n8 n9
n1 n4
n3 n5
To find the root, left and right sub trees for n7 n8 and n9:
From the postorder sequence n8 n7 n9, the root of the left sub tree
is: n9
From the inorder sequence n7 n8 n9, we can find that n7 and n8 are to
the left of n9 and no right subtree for n9.
n6
n2 n9
n1 n4 n7 n8
n3 n5
To find the root, left and right sub trees for n7 and n8:
From the postorder sequence n8 n7, the root of the tree is: n7
From the inorder sequence n7 n8, we can find that there is no left subtree
for n7 and n8 is to the right of n7. The Binary tree upto this point looks
like:
n6
n2 n9
n1 n4 n7
n3 n5 n8
©Topperworld
Data Structure and Algorithms
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int data;
TreeNode left;
TreeNode right;
public BinaryTreeOperations() {
root = null;
}
©Topperworld
Data Structure and Algorithms
©Topperworld
Data Structure and Algorithms
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
System.out.print(current.data + " ");
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
}
printLeafNodes(node.left);
printLeafNodes(node.right);
}
System.out.println("Inorder Traversal:");
©Topperworld
Data Structure and Algorithms
tree.inorderTraversal(tree.root);
System.out.println();
System.out.println("Preorder Traversal:");
tree.preorderTraversal(tree.root);
System.out.println();
System.out.println("Postorder Traversal:");
tree.postorderTraversal(tree.root);
System.out.println();
System.out.println("Leaf Nodes:");
tree.printLeafNodes(tree.root);
System.out.println();
OUTPUT:-
Inorder Traversal:
4251637
Preorder Traversal:
1245367
Postorder Traversal:
4526731
Leaf Nodes:
4567
©Topperworld
Data Structure and Algorithms
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int data;
TreeNode left;
TreeNode right;
public BinaryTreeOperations() {
root = null;
}
©Topperworld
Data Structure and Algorithms
©Topperworld
Data Structure and Algorithms
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
System.out.print(current.data + " ");
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
}
printLeafNodes(node.left);
printLeafNodes(node.right);
}
©Topperworld
Data Structure and Algorithms
if (deleteLastNode(node.right)) {
node.right = null;
return true;
}
if (deleteLastNode(node.left)) {
node.left = null;
return true;
}
return false;
}
System.out.println("Inorder Traversal:");
tree.inorderTraversal(tree.root);
System.out.println();
System.out.println("Preorder Traversal:");
tree.preorderTraversal(tree.root);
System.out.println();
System.out.println("Postorder Traversal:");
tree.postorderTraversal(tree.root);
System.out.println();
©Topperworld
Data Structure and Algorithms
tree.levelOrderTraversal(tree.root);
System.out.println();
System.out.println("Leaf Nodes:");
tree.printLeafNodes(tree.root);
System.out.println();
height = tree.findHeight(tree.root);
System.out.println("Height of the Tree after deletion: " +
height);
}
}
OUTPUT:-
Inorder Traversal:
4251637
Preorder Traversal:
1245367
Postorder Traversal:
4526731
Leaf Nodes:
4567
©Topperworld
Data Structure and Algorithms
At first glance, it appears that we would always want to use the flat
traversal functions since they use less stack space. But the flat versions
are not necessarily better. For instance, some overhead is associated with
the use of an explicit stack, which may negate the savings we gain from
storing only node pointers. Use of the implicit function call stack may
actually be faster due to special machine instructions that can be used.
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each
vertex onto the stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a
vertex with right son exists, then set right son of vertex as current
vertex and return to step one.
©Topperworld
Data Structure and Algorithms
Algorithm inorder()
{
stack[1] = 0
vertex = root
top: while(vertex ≠ 0)
{
push the vertex into the
stack vertex =
leftson(vertex)
}
while(vertex ≠ 0)
{
print the vertex node
if(rightson(vertex) ≠ 0)
{ vertex =
rightson(vertex)
goto top
}
pop the element from the stack and made it
as vertex
}
}
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex
onto stack, if any and process each vertex. The traversing ends after
a vertex with no left child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one
otherwise exit.
©Topperworld
Data Structure and Algorithms
Algorithm preorder( )
{
stack[1] = 0 vertex =
root.
while(vertex ≠ 0)
{
print vertex node
if(rightson(vertex) ≠ 0) push the right son of vertex into the stack.
if(leftson(vertex) ≠ 0)
vertex = leftson(vertex)
else
pop the element from the stack and made it as vertex
}
}
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex. At each vertex of
path push vertex on to stack and if vertex has a right son push –
(right son of vertex) onto stack.
2. Pop and process the positive nodes (left nodes). If zero is popped
then exit. If a negative node is popped, then ignore the sign and
return to step one.
©Topperworld
Data Structure and Algorithms
Algorithm postorder( )
{
stack[1] = 0
vertex = root
top: while(vertex ≠ 0)
{
push vertex onto stack
if(rightson(vertex) ≠ 0)
push – (vertex) onto stack
vertex = leftson(vertex)
}
pop from stack and make it as vertex
while(vertex > 0)
{
print the vertex node
pop from stack and make it as vertex
}
if(vertex < 0)
{
vertex = - (vertex)
goto top
}
}
Example 1:
Traverse the following binary tree in pre, post and inorder using non-
recursive traversing algorithm.
A
• Preorder traversal yields:
B C A, B, D, G, K, H, L, M, C, E
D E
• Postorder travarsal yields:
G H K, G, L, M, H, D, B, E, C, A
©Topperworld
Data Structure and Algorithms
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each
vertex onto the stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a
vertex with right son exists, then set right son of vertex as current
vertex and return to step one.
CURRENT PROCESSED
STACK REMARKS
VERTEX NODES
A 0 PUSH 0
0ABDG PUSH the left most path of
K A
K 0ABDG K POP K
POP G since K has no right
G 0ABD KG
son
POP D since G has no right
D 0AB KGD
son
Make the right son of D as
H 0AB KGD
vertex
0ABHL KGD PUSH the leftmost path of H
©Topperworld
Data Structure and Algorithms
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex. At each vertex of
path push vertex on to stack and if vertex has a right son push –
(right son of vertex) onto stack.
2. Pop and process the positive nodes (left nodes). If zero is popped
then exit. If a negative node is popped, then ignore the sign and
return to step one.
CURRENT PROCESSED
STACK REMARKS
VERTEX NODES
A 0 PUSH 0
0 A –C B D –H PUSH the left most path of
GK A with a -ve for right sons
0 A –C B D –H K G POP all +ve nodes K and G
H 0 A –C B D KG Pop H
0 A –C B D H – PUSH the left most path of
KG
ML H with a -ve for right sons
0 A –C B D H –
L KGL POP all +ve nodes L
M
M 0 A –C B D H KGL Pop M
PUSH the left most path of
0 A –C B D H M K G L
M with a -ve for right sons
POP all +ve nodes M, H, D
0 A –C KGLMHDB
and B
©Topperworld
Data Structure and Algorithms
C 0A KGLMHDB Pop C
PUSH the left most path of
0ACE KGLMHDB
C with a -ve for right sons
K GLMHDBE POP all +ve nodes E, C and
0
C A A
K GLMHDBE
0 Stop since stack is empty
C A
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex
onto stack, if any and process each vertex. The traversing ends after
a vertex with no left child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one
otherwise exit.
CURRENT PROCESSED
STACK REMARKS
VERTEX NODES
A 0 PUSH 0
PUSH the right son of each vertex
0CH ABDGK onto stack and process each vertex
in the left most path
H 0C ABDGK POP H
PUSH the right son of each vertex
0CM ABDGKHL onto stack and process each vertex
in the left most path
M 0C ABDGKHL POP M
PUSH the right son of each vertex
onto stack and process each vertex
0C ABDGKHLM
in the left most path; M has no left
path
C 0 A B D G K H L M Pop C
©Topperworld
Data Structure and Algorithms
Example 2:
Traverse the following binary tree in pre, post and inorder using non-
recursive traversing algorithm.
Inorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex, pushing each
vertex onto the stack and stop when there is no left son of vertex.
2. Pop and process the nodes on stack if zero is popped then exit. If a
vertex with right son exists, then set right son of vertex as current
vertex and return to step one.
©Topperworld
Data Structure and Algorithms
2 0
027
2
2 027 2
7 02 27
6 026 27
5
5 026 275
6 02 2756
11 0 2 11 2 7 5 6
11 02 2 7 5 6 11
2 0 2 7 5 6 11 2
5 05 2 7 5 6 11 2
5 0 2 7 5 6 11 2 5
9 094 2 7 5 6 11 2 5
4 09 2 7 5 6 11 2 5
4
9 0 2 7 5 6 11 2 5 Stop since stack is
49 empty
Postorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path rooted at vertex. At each vertex of
path push vertex on to stack and if vertex has a right son push –
(right son of vertex) onto stack.
2. Pop and process the positive nodes (left nodes). If zero is popped
then exit. If a negative node is popped, then ignore the sign and
return to step one.
©Topperworld
Data Structure and Algorithms
0 2 –5 7 –6
2
2 0 2 –5 7 –6 2
6 0 2 –5 7 2
0 2 –5 7 6 – 2
11 5
5 0 2 –5 7 6 – 25
11
11 0 2 –5 7 6 25
11
0 2 –5 2 5 11 6 7
5 0 2 5 –9 2 5 11 6 7
9 02594 2 5 11 6 7
Preorder Traversal:
Initially push zero onto stack and then set root as vertex. Then repeat the
following steps until the stack is empty:
1. Proceed down the left most path by pushing the right son of vertex
onto stack, if any and process each vertex. The traversing ends after
a vertex with no left child exists.
2. Pop the vertex from stack, if vertex ≠ 0 then return to step one
otherwise exit.
056 272
6 0 5 11 2 7 2 6 5
©Topperworld
Data Structure and Algorithms
11 05 2 7 2 6 5 11
05 2 7 2 6 5 11
5 09 2 7 2 6 5 11 5
9 0 2 7 2 6 5 11 5
94
0 2 7 2 6 5 11 5 Stop since stack is
94 empty
Expression Trees:
Expression tree is a binary tree, because all of the operations are binary.
It is also possible for a node to have only one child, as is the case with the
unary minus operator. The leaves of an expression tree are operands, such
as constants or variable names, and the other (non leaf) nodes contain
operators.
• Inorder Traversal
• Preorder Traversal
• Postorder Traversal
©Topperworld
Data Structure and Algorithms
+ +
+ / + d
a b c d + c
+ *
- + + *
a x y b c a
An expression tree can be generated for the infix and postfix expressions.
Example 1:
Solution:
©Topperworld
Data Structure and Algorithms
The first two symbols are operands, so we create one-node trees and push
pointers to them onto a stack.
a b
Next, a ‘+’ is read, so two pointers to trees are popped, a new tree is
formed, and a pointer to it is pushed onto the stack.
a b
Next, c, d, and e are read, and for each one–node tree is created and a
pointer to the corresponding tree is pushed onto the stack.
a b c d e
+
+ c +
a bb d e
Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree
with a ‘*’ as root.
©Topperworld
Data Structure and Algorithms
+
+ *
a b c +
d ee
Finally, the last symbol is read, two trees are merged, and a pointer to the
final tree is left on the stack.
+
*
+ *
a b c +
d e
e
Example 2:
(A + B * C) – ((D * E + F) / G)
Solution:
First convert the infix expression into postfix notation. Postfix notation of
the arithmetic expression is: A B C * + D E * F + G / -
©Topperworld
Data Structure and Algorithms
The first three symbols are operands, so we create one-node trees and
pointers to three nodes pushed onto the stack.
A B C
Next, a ‘*’ is read, so two pointers to trees are popped, a new tree is
formed, and a pointer to it is pushed onto the stack.
A *
B C
Next, a ‘+’ is read, so two pointers to trees are popped, a new tree is
formed, and a pointer to it is pushed onto the stack.
A
*
B C
Next, D and E are read, and for each one–node tree is created and a pointer
to the corresponding tree is pushed onto the stack.
+ D E
A
*
B C
Continuing, a ‘*’ is read, so we pop two tree pointers and form a new tree
with a ‘*’ as root.
©Topperworld
Data Structure and Algorithms
+ *
A * D E
B C
Proceeding similar to the previous steps, finally, when the last symbol is
read, the expression tree is as follows:
+
-
+ /
A * + G
B C * F
D E
Let us convert the following expressions from one type to another. These
can be as follows:
1. Postfix to infix
2. Postfix to prefix
3. Prefix to infix
4. Prefix to postfix
1. Postfix to Infix:
The following algorithm works for the expressions whose infix form does
not require parenthesis to override conventional precedence of operators.
©Topperworld
Data Structure and Algorithms
2. Postfix to Prefix:
3. Prefix to Infix:
The following algorithm works for the expressions whose infix form does
not require parenthesis to override conventional precedence of operators.
4. Prefix to postfix:
The linked representation of any binary tree has more null links than actual
pointers. If there are 2n total links, there are n+1 null links. A clever way
to make use of these null links has been devised by A.J. Perlis and C.
Thornton.
Their idea is to replace the null links by pointers called Threads to other
nodes in the tree.
©Topperworld
Data Structure and Algorithms
B C
D E F G
H I
B C
D E F G
H I
The tree has 9 nodes and 10 null links which have been replaced by
Threads. If we traverse T in inorder the nodes will be visited in the order H
D I B E A F C G.
For example, node ‘E’ has a predecessor Thread which points to ‘B’ and a
successor Thread which points to ‘A’. In memory representation Threads
and normal pointers are distinguished between as by adding two extra one
bit fields LBIT and RBIT.
©Topperworld
Data Structure and Algorithms
1. Every element has a key and no two elements have the same key.
2. The keys in the left subtree are smaller than the key in the root.
3. The keys in the right subtree are larger than the key in the root.
4. The left and right subtrees are also binary search trees.
Figure is a binary search tree, whereas figure 5.2.5(b) is not a binary search
tree.
16 16
12 20 12 20
11 14 19 11 14 19
7
13 13 17
©Topperworld
Data Structure and Algorithms
If in a tree, the outdegree of every node is less than or equal to m, the tree
is called general tree. The general tree is also called as an m-ary tree. If
the outdegree of every node is exactly equal to m or zero then the tree is
called a full or complete m-ary tree. For m = 2, the trees are called
binary and full binary trees.
Each element in a tree can have any Each element in a binary tree has at
number of subtrees. most two subtrees.
Stage 1:
• We draw edges from a node to the node on the right, if any, which
is situated at the same level.
Stage 2:
©Topperworld
Data Structure and Algorithms
• Once this is done then for any particular node, we choose its left
and right sons in the following manner:
• The left son is the node, which is immediately below the given
node, and the right son is the node to the immediate right of the
given node on the same horizontal line. Such a binary tree will not
have a right subtree.
Example 1:
2 3 4 5
6 7 8 9 10 11
Solution:
Stage 1
tree by using the above mentioned procedure is as follows:
1
2 3 4 5
6 7 8 9 10 11
6 3
7 8 4
10
11
©Topperworld
Data Structure and Algorithms
Example 2:
2 3 8 9 10
4 5 6 11 12 13
0
Solution:
2 3 8 9 10
4 5 6 11 12 13
2 7
4 3 8
5 6 11 9
9
10
12
13
Example 3:
©Topperworld
Data Structure and Algorithms
B F J
C D E G H K L M N
P Q
General tree T
Solution:
1. Stage 1:
B F J
C D E G B
H
5 K L M N
P Q
Stage 2:
©Topperworld
Data Structure and Algorithms
C F
D G J
10
E H K
L
Binart tree T’
P N
Preorder:
1) Process the root R.
2) Traverse the subtree T1, T2, ……., TM in preorder.
Postorder:
1) Traverse the subtree T1, T2, ……., TM in postorder.
2) Process the root R.
The tree T has the root A and subtrees T1, T2 and T3 such that:
T1 consists of nodes B, C, D and E.
T2 consists of nodes F, G and H.
T3 consists of nodes J, K, L, M, N, P and Q.
©Topperworld
Data Structure and Algorithms
Preorder: A, B, C, D, E, F, G, H, J, K, M, P, Q, N
Inorder: C, D, E, B, G, H, F, K, L, P, Q, M, N, J, A
Postorder: E, D, C, H, G, Q, P, N, M, L, K, J, F, B, A
©Topperworld
Data Structure and Algorithms
In Depth first search, we begin with root as a start state, then some
successor of the start state, then some successor of that state, then some
successor of that and so on, trying to reach a goal state. One simple way
to implement depth first search is to use a stack data structure consisting
of root node as a start state.
A
E
START J
S B
H G GOAL
C F
K
I
Suppose S is the start and G is the only goal state. Depth first search will
first visit S, then A, then D. But D has no successors, so we must back up
to A and try its second successor, E. But this doesn’t have any successors
either, so we back up to A again. But now we have tried all the successors
of A and haven’t found the goal state G so we must back to ‘S’. Now ‘S’ has
a second successor, B. But B has no successors, so we back up to S again
and choose its third successor, C. C has one successor, F. The first
successor of F is H, and the first of H is J. J doesn’t have any successors,
so we back up to H and try its second successor. And that’s G, the only
goal state.
©Topperworld
Data Structure and Algorithms
So the solution path to the goal is S, C, F, H and G and the states considered
were in order S, A, D, E, B, C, F, H, J, G.
Disadvantages:
1. It works very fine when search graphs are trees or lattices, but
can get struck in an infinite loop on graphs. This is because depth
first search can travel around a cycle in the graph forever.
A
E
START J
S B
H G GOAL
C F
K
I
Breadth first search finds states level by level. Here we first check all the
immediate successors of the start state. Then all the immediate successors
of these, then all the immediate successors of these, and so on until we
find a goal node. Suppose S is the start state and G is the goal state. In
the figure, start state S is at level 0; A, B and C are at level 1; D, e and F
at level 2; H and I at level 3; and J, G and K at level 4.
©Topperworld
Data Structure and Algorithms
Breadth first search does not have the danger of infinite loops as we
consider states in order of increasing number of branches (level) from the
start state.
One simple way to implement breadth first search is to use a queue data
structure consisting of just a start state.
Sparse Matrices:
(3, 1) 1
(2, 2) 2
S = (3, 2) 3
(4, 3) 4
(1, 4) 5
The printed output lists the non-zero elements of S, together with their row
and column indices. The elements are sorted by columns, reflecting the
internal data structure. In large number of applications, sparse matrices
are involved. One approach is to use the linked list.
The program to represent sparse matrix:
import java.util.Scanner;
public class SparseMatrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
©Topperworld
Data Structure and Algorithms
System.out.println("Original Matrix:");
printMatrix(matrix);
if (isSparse(matrix)) {
System.out.println("The given matrix is a sparse
matrix.");
int[][] compactMatrix = convertToCompactForm(matrix);
System.out.println("Compact Form of the Matrix:");
printMatrix(compactMatrix);
} else {
System.out.println("The given matrix is not
sparse.");
}
}
public static boolean isSparse(int[][] matrix) {
int zeroCount = 0;
int totalElements = matrix.length * matrix[0].length;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
zeroCount++;
}
}
}
// If more than half of the elements are zero, it's
considered sparse.
return zeroCount > (totalElements / 2);
}
public static int[][] convertToCompactForm(int[][] matrix) {
int numRows = matrix.length;
©Topperworld
Data Structure and Algorithms
OUTPUT 1:-
Enter the number of rows: 3
Enter the number of columns: 4
©Topperworld
Data Structure and Algorithms
OUTPUT 2:-
Enter the number of rows: 2
Enter the number of columns: 2
Enter the matrix elements:
12
34
Original Matrix:
1 2
3 4
The given matrix is not sparse.
©Topperworld