0% found this document useful (0 votes)
3 views49 pages

Binary Tree Algorithms

The document outlines various algorithms related to binary trees, including counting nodes, leaf nodes, nodes with one or two children, and calculating height and balance factors. It also discusses tree creation and traversal methods, such as pre-order, in-order, and post-order traversals, as well as how to build trees using traversal data. Additionally, it covers the conditions for a binary tree to be complete or strictly binary.

Uploaded by

rajatmaurya7906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views49 pages

Binary Tree Algorithms

The document outlines various algorithms related to binary trees, including counting nodes, leaf nodes, nodes with one or two children, and calculating height and balance factors. It also discusses tree creation and traversal methods, such as pre-order, in-order, and post-order traversals, as well as how to build trees using traversal data. Additionally, it covers the conditions for a binary tree to be complete or strictly binary.

Uploaded by

rajatmaurya7906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

10.

1 Binary Tree Algorithms

10.1.1 Finding Count of Nodes in the Tree


If the node does not exist, its counting is updated as zero. If the node exists, then the number
of nodes considering that as root node will be the 1 (the count of that node) plus the nodes in
the Left subtree and Right subtree of that node computed recursively.

ALGORITHM CountNodes(Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
RETURN 1+CountNodes(Root Left) + CountNodes(Root Right)
END;

10.1.2 Finding the count of Leaf Nodes


If the node does not exist, the count of the leaf will be 0. If the left and right of a node are
NULL, that will be the leaf node, and its counting is updated as 1. If the node exists and it is not
the leaf node, then the number of leaf nodes considering that as root node will be the sum of
leaf nodes on the Left subtree and Right subtree of that node computed recursively.

ALGORITHM CountLeafNodes(Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft==NULL AND RootRight ==NULL THEN
RETURN 1
ELSE
RETURN CountLeafNodes(RootLeft)+CountLeafNodes(RootRight)
END;
10.1.3 Finding the count of Nodes having one Child
If the node does not exist, the count of N1 nodes will be 0. If the left and right of a node are
NULL, that will be the leaf node, and it cannot be the N1 node; hence count is updated as 0. If
the node exists and it's one of the child is NULL, then it is definitely the N1 Node and its
counting is taken as 1, but there could be more N1 nodes in the subtree starting from that node
(found recursively). If both the children exist for the given node, that node cannot be N1 node,
but there could be some N1 nodes in the subtree starting from there. These are counted
recursively by counting the sum of N1 nodes on the Left subtree and Right subtree of that node.

ALGORITHM CountN1Nodes(Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft==NULL AND Root  Right ==NULL THEN
RETURN 0
ELSE
IF RootLeft!=NULL AND Root  Right !=NULL THEN
RETURN CountN1Nodes(Root Left) + CountN1Nodes(RootRight)
ELSE
RETURN 1+ CountN1Nodes(RootLeft) +CountN1Nodes(RootRight)
END;
10.1.4 Finding the count of Nodes having Two Children
If the node does not exist, the count of N2 nodes will be 0. If the left and right of a node are
NULL, that will be the leaf node and it cannot be the N2 node, hence count is updated as 0. If
both the children exist for the given node then it is definitely the N2 Node and its counting is
taken as 1, but there could be more N2 nodes in the subtree starting from that node (found
recursively). If the node exists and its one of the child is NULL, that node cannot be N2 node,
but there could be some N2 nodes in the subtree starting from there, these are counted
recursively by counting the sum of N2 nodes on the Left subtree and Right subtree of that node.

ALGORITHM CountN2Nodes(Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft==NULL AND Root  Right ==NULL THEN
RETURN 0
ELSE
IF RootLeft!=NULL AND Root  Right !=NULL THEN
RETURN 1+ CountN1Nodes(RootLeft)+CountN1Nodes(RootRight)
ELSE
RETURN CountN1Nodes (RootLeft) + CountN1Nodes (RootRight)
END;
10.1.5 Finding Height of a node
If the node does not exist, its height is counted as zero. If a node is a left node, its height is
counted as 0. Otherwise, find the height of the left subtree and right subtree recursively, take a
maximum of both and add 1 to it. This will be the height of the given node.

ALGORITHM Height (Root)


BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft==NULL AND Root  Right ==NULL THEN
RETURN 0
ELSE
RETURN 1+ Height(Root Left) + Height(Root Right)
END;
Method 2 (Through Left height and right height)
ALGORITHM Height (Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft == NULL THEN
Lh =0
ELSE
Lh = 1+Height(RootLeft)

IF RootRight == NULL THEN


Rh =0
ELSE
Rh = 1+Height(RootLeft)

RETURN Maximum(Lh,Rh)
END;

10.1.6 Finding Balance Factor of a Node


The balance factor of a node is the difference of height of the node on the left subtree and right
subtree.
ALGORITHM BalanceFactor (Root)
BEGIN:
IF Root == NULL THEN
RETURN 0
ELSE
IF RootLeft == NULL THEN
Lh =0
ELSE
Lh = 1+Height(RootLeft)

IF RootRight == NULL THEN


Rh =0
ELSE
Rh = 1+Height(RootLeft)

RETURN Lh - Rh
END;

10.1.7 Finding if the given Binary Tree is complete


A binary tree is complete if this relation is satisfied between number of nodes (N) and Height
(H)
N = 2(H+1) – 1
ALGORITHM IsComplete (Root)
BEGIN:
N=CountNodes(Root)
H=Height(Root)
IF Power(2, H+1) – 1 == N THEN
RETURN TRUE
ELSE
RETURN FALSE
END;

10.1.8 Find if Binary Tree is strictly


A Binary Tree is considered a strictly binary tree if all the nodes in the tree have either zero
child or two child. This can be computed in 2 ways. In the first, find out N1 nodes by the
function defined in the above text. If the count of N1 nodes is zero, that tree is definitely
strictly. The second method recursively checks the condition of both the children recursively.

ALGORITHM IsStrictly (Root)


BEGIN:
IF Root == NULL THEN
RETURN TRUE
ELSE
IF RootLeft == NULL AND RootRight == NULL THEN
RETURN TRUE
ELSE
IF RootLeft!=NULL AND RootRight !=NULL THEN
RETURN IsStrictly(RootLeft) AND IsStrictly(RootRight)
ELSE
RETURN FALSE
END;

10.2 Creation of Binary Tree

The given function creates the binary tree by asking the user about its structure. First, it
enquires about the root node, then about the left, and finally about the right subtree. For every
newly created node, the function recursively calls itself to enquire about the left and right
subtree of that node.
ALGORITHM CreateBinaryTree(root)
BEGIN:
IF root==NULL THEN
/***** Enquiry about the root Node *****/
WRITE("Input the data of root node ");
READ(x);
q=GetNode(x)
root=q;
CreateBinaryTree(root);
ELSE
/***** Enquiry about the left Node *****/
WRITE("Whether left of root exists?(1/0)")
READ(choice)
IF choice==1 THEN
WRITE("Input the data of left node ");
READ(x);
q=GetNode(x)
root->left=q;
CreateBinaryTree(root);
/***** Enquiry about the right Node *****/
WRITE("Whether right of root exists?(1/0)")
READ(choice)
IF choice==1 THEN
WRITE("Input the data of right node ");
READ(x);
q=GetNode(x)
root->right=q;
CreateBinaryTree(root);
END;

10.3 Tree Traversals

DOM is the real-world example, where the concept of tree traversal is used. Here DOM is
organized as a tree, and the node of the document which itself is present at the root node while
we search any element by using keyword document.getElementbyID.
There are two approaches that are used while performing traversing in the tree. These are
based upon DFS and BFS. With the help of DFS we, can do pre-order, in order, and post order
traversing and with the help of BFS, we can do Level order traversing in a tree. Let us see these
techniques one by one briefly: -

DFS: In Depth First Search, we go to the deepest level of the tree, and once we reached the
node that is not having any children, we back track till the point, we find the node whose child
is yet to be traversed. This technique is used in pre-order traversal, post-order traversal and in
order traversal.
Analogy: - Just like a maze game, we start with a given direction and kept on traversing that
path till we found a dead end. Sooner we find the dead-end, we backtrack till the point where
another path can be found.
BFS: In BFS, we are traversing the nodes level by level. We are traversing any child of node only
after traversing all its siblings.
Example: - Level order traversal.

10.3.1 Pre-order Traversing


Pre-order traversing is used to find prefix expression. Pre-order traversing is done by using the
following steps. These are: -
1) Visit the Root Node and print the data part.
2) Recursively traverse the left subtree.
3) Recursively Traverse the Right subtree.

Diagrammatic Representation
Step 1

Step 2
Step 3

Step 4

Step 5
Step 6

Step 7
Step 8

Step 9

Step 10
Step 11

Step 12

Step 13
ALGORITHM Preorder_traversal(Root)
BEGIN:
IF root == NULL THEN
RETURN 0
ELSE
WRITE (root  Data)
Preorder_Traversal(root Left)
Preorder_Traversal(root  Right)
END;

10.3.2 In-order Traversing


In In-order traversing, we compute the following steps. These are
1) Recursively visit Left Subtree
2) Visit Root Node. Write data part.
3) Recursively call Right Subtree

Diagrammatic Representation

Step 2 Step 3

Step 5 Step 4
Step 6

Step 7

Step 8
Step 9

Step 10
Step 11

Step 12

Step 13
Step 14

Step 15

Step 16
Step 17

Step 18
Step 19

Step 20

ALGORITHM Inorder_traversal(Root)
BEGIN:
IF root == NULL THEN
RETURN 0;
ELSE
Inorder_traversal(rootLeft)
WRITE (rootData)
Inorder_traversal(rootRight)
END;

10.3.3 Post order Traversing


In Post order traversing, we compute the following steps. These are
1) Recursively visit Left Subtree
2) Recursively call Right Subtree
3) Visit Root Node. Write data part.

Diagrammatic Representation
ALGORITHM Postorder_traversal( Root)
BEGIN:
IF root == NULL THEN
RETURN 0;
ELSE
Postorder_traversal(rootLeft)
Postorder_traversal(rootRight)
WRITE (rootData)
END;
10.4 Tree Conversion

10.4.1 Building of tree using Inorder Tree Traversal and Preorder Tree Traversal
We can build a tree using Inorder and Preorder Traversal; the first node in preorder traversal
will be root node. Using Inorder Traversal, we can determine the left subpart of the tree and
the right subpart of the tree.
Preorder: 3, 9, 20, 15, 7
In order: 9, 3, 15, 20, 7
Step 1
Preorder: 3, 9, 20, 15, 7 (3 will be the root of tree)
In order: 9, 3, 15, 20, 7 ( Left Root Right).
Here 3 is root of tree, so 9 will lie on LHS, and 15, 20, 7 will lie on RHS

Step 2
Preorder: 3, 9, 20, 15, 7 (3 will be the root of tree)
In order: 9, 3, 15, 20, 7(Left Root Right).
Here 9 is the root of subtree, so nothing on LHS and nothing will lie on RHS

Step 3

Preorder: 3, 9, 20, 15, 7 (20 will be the root of tree)


In order: 9, 3, 15, 20, 7(Left Root Right).
Here 20 is the root of subtree, so 15 on LHS and 20 will lie on RHS.
Complexity: - O (n2)

Building of tree using Inorder Tree Traversal and Preorder Tree Traversal
ALGORITHM Build_Tree(Preorder [], Inorder [], n)
BEGIN:
PreStart = 0
PreEnd = n-1 // n is number of elements
InorderStart = 0
InorderEnd = n-1 // n is number of elements
RETURNConstruct (Preorder, Inorder, Prestart, PreEnd, InorderStart, InorderEnd)
END;

ALGORITHM Construct(Preorder [], Inorder[], Prestart, PreEnd,InorderStart, InorderEnd)


BEGIN:
IF Prestart >PreEnd || InorderStart>InorderEnd THEN
RETURN NULL

Val = Preorder [Prestart]


P=GetNode(Val)
FOR i=0 TO Inorder.length() DO
IF Val == inorder[i] THEN
k=i
BREAK

Pleft = Construct (Preorder, Inorder, Prestart + 1, PreStart + (k – InorderStart),


InorderStart, k-1)

Pright = construct (Preorder, Inorder, Prestart + (k – InorderStart)+ 1, PreEnd , k+1,


InorderEnd)
RETURN P
END;

10.4.2 Building of tree using Inorder Tree Traversal and Postorder Tree Traversal
We can build a tree using Inorder and Post-order Traversal; the last node in Post-order traversal
will be the root node. Using Inorder Traversal, we can determine the left subpart of the tree
and the right sub part of the tree.
Postorder: 9, 1, 2, 12, 7, 5, 3, 11, 4, 8.
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Step 1
Postorder: 9, 1, 2, 12, 7, 5, 3, 11, 4, 8. (Last element in Postorder traversal will be 8.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have 9,5,1,7,2,12 and Right Subtree will have 4, 3, 11.
Root will be 8

Step 2
Postorder: 9, 1, 2, 12, 7, 5, 3, 11, 4, 8. (Last element in Postorder traversal will be 4.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have nothing and Right Subtree will have 3, 11.
Root will be 4

Step 3
Postorder: 9, 1, 2, 12, 7, 5, 3, 11, 4, 8. (Last element in Postorder traversal will be 11.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have 3, and Right Subtree will have nothing.
Root will be 11
Step 4
Postorder: 9, 1, 2, 12, 7, 5, 3, 11, 4, 8. (Last element in Postorder traversal will be 11.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have nothing, and Right Subtree will have nothing.
Root will be 3.

Step 5
Postorder: 9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 5.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have 9, and Right Subtree will have 1,7,2,12.
Root will be 5.

Step 5
Postorder: 9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 7.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have 1, and Right Subtree will have 2,12.
Root will be 7.

Step 6
Postorder: 9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 12.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have 2 and Right Subtree will have nothing.
Root will be 12.

Step 7: -
Postorder: 9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 2.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have nothing and Right Subtree will have nothing.
Root will be 2.
Step 8
Postorder: 9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 1.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have nothing, and Right Subtree will have nothing.
Root will be 1.

Step 9
Postorder:9, 1, 2, 12, 7, 5,3, 11, 4, 8. (Last element in Postorder traversal will be 9.)
In order: 9, 5, 1, 7, 2, 12, 8, 4,3, 11.
Left Subtree will have nothing, and Right Subtree will have nothing.
Root will be 9.
Algorithm for building Tree from Postorder and Inorder Traversal
ALGORITHM Build_Tree(Postorder [], Inorder [], n)
BEGIN:
PostStart = 0
PostEnd = n-1 // n is number of elements
InorderStart = 0
InorderEnd = n-1 // n is number of elements
RETURNConstruct (Inorder, Postorder, InorderStart, InorderEnd, PostStart, PostEnd)
END;

ALGORITHM Construct (Inorder[], Postorder[], InorderStart, InorderEnd, PostStart, PostEnd)


BEGIN:
IF Poststart>PostEnd || InorderStart>InorderEnd THEN
RETURN NULL
Val = Postorder [Postend];
P=GetNode()
FOR i=0 TO Inorder.length()DO
IF Val == inorder[i] THEN
k=i
BREAK
Pleft = Construct (Inorder,Postorder, InorderStart, k-1, PostStart, PostStart + k -
(Inorderstart+1))
Pright = construct (Inorder, Postorder, k+1, InorderEnd, Poststart +k –InorderStart,
PostEnd -1)
RETURN P
END;

Complexity
Time Complexity: - O (n2)
Space Complexity :- O(n)

Example: -
Inorder :- 9, 3, 15, 20, 7
Postorder :- 9, 15, 7, 20, 3
Step 1
Inorder :- 9, 3, 15, 20, 7
Postorder :- 9, 15, 7, 20, 3 (3 will be root).
3 will be root of tree, 9 will be left subtree and 15, 20, 7 will be on Right subpart.

Step 2
Left Subpart consists of node 9; on searching node 9 in postorder traversal, the node has
been found at index one.

Inorder :- 9, 3, 15, 20, 7


Postorder :- 9, 15, 7, 20, 3 (9 will be root).
9 will be root of subtree, no node will be left subtree and np node will be on Right subpart.

Step 3
Left Subpart does not contain any node; on searching 15, 20, 7 for right subpart, node 20 was
found as a root on postorder traversal.
Inorder :- 9, 3, 15, 20, 7
Postorder :- 9, 15, 7, 20, 3 (20 will be root).
20 will be the root of the subtree, 15 will be the left subtree, and 7 will be on the Right
subpart.

Step 4
Left Subpart contain node 15. 15 is marked with red color in postorder traversal
Inorder :- 9, 3, 15, 20, 7
Postorder :- 9, 15, 7, 20, 3 (20 will be root).
15 will be root of sub tree, no node will be left subtree and no node will be on Right subpart.

Step 5
The left Subpart does not contain any node. The right subpart of node 20 contains node 7.
Inorder :- 9, 3, 15, 20, 7
Postorder :- 9, 15, 7, 20, 3 (20 will be root).
15 will be root of subtree, no node will be left subtree, and no node will be on the Right
subpart.
10.5 Top View Traversal

The focus is to find the top-view of a tree using recursion. The top-view of a tree is actually that
view of a tree in which when we view the tree from the top, and only those nodes which are
visible from the top will be the part of top-view traversal.
One way to find top-view is by looking for horizontal distance, just like a number line pattern.
So, horizontal distance to each node is given from the root node of its level. Every node to the
left of its root will be subtracted by 1 from its root distance and right will be added by 1.
So we can say that,
1. If for root node Horizontal Distance(HD) = 0
2. Then for left child HD = HD-1(from its parent node)
3. Then for right child HD= HD+1(from its parent node)
Let us demonstrate it with an example:

From the above example we can see horizontal distance of:


A, E --> 0
B, G -->-1
C, H --> 1
D -->-2
I --> 2
J --> 3
In the above example, we can see that few nodes have the same Horizontal Distance, but as we
see from the top, we find that the nodes which have lower level will be visible and all inner
nodes are overshadowed.
In the above figure, top-view will consist of nodes : D B A C I J
Create a Map-Table that stores pair of nodes and level corresponding to distance from the root.

10.5.1 TopView Recursive approach

ALGORITHM TopView( Root, DIST, LEVEL)


//Root is node at each level, DIST means distance and LEVELdenotes level of tree
BEGIN:
IF Root== NULL THEN
RETURN
IF M[DIST]== Φ or M[DIST] > LEVEL THEN
M[DIST]= pairof(Root, LEVEL)
TopView(Root-->Left, DIST-1, LEVEL+1)
TopView(Root-->Right, DIST+1, level+1)
WRITE(values in sorted order of DIST index of map-Table M)
END;
Time Complexity: O(nlogn) as there is n number of nodes and logn is the insertion time it takes
to insert in a map-table.

10.5.2 Step-wise explanation

1. The root node, distance and level is passed as parameter. Initially, for above example A,
0, 0.
2. Check if the node passed is empty or has the address.
3. Check whether the distance passed already present in Map-Table.
4. If not, maintain its entry in Map-Table. For example 0 --> {A,0}
5. Recursively call the TopView function for the left of the current node.
6. If the left node is empty recursively, call the TopView function for the right of the
current node.
The below step-wise figures give a better view of TopView binary tree traversal.
10.6 Bottom View
Unlike top view traversal in bottom view traversal, those nodes will be picked which are at a
higher level since the view of the tree is from the bottom. The process remains the same by
first finding the Horizontal Distance and then by checking the level of the node.
The demonstration of the same can be done by the previous example:
From the above example we can find horizontal distance of each node:
A, E--> 0
B, G -->-1
C, H--> 1
D -->-2
I --> 2
J --> 3
In the above example, we can see that few nodes have the same Horizontal Distance, but as we
see from the bottom, we find that the nodes which have a higher level will be visible, and all
lower level nodes are overshadowed.

In the above figure, the bottom-view will consist of nodes: D GEH I J


Create a Map-Table that stores pair of nodes and level corresponding to distance from root.

10.6.1 BottomView Recursive approach


ALGORITHM BottomView( Root, DIST, LEVEL)
//Root is node at each level, DIST means distance and LEVEL denotes level of tree
BEGIN:
IF Root== NULL THEN
RETURN
IF M[DIST]== Φ or M[DIST] < LEVEL THEN
M[DIST]= pairof(Root, LEVEL)
TopView(Root-->Left, DIST-1, LEVEL+1)
TopView(Root-->Right, DIST+1, level+1)
WRITE( values in sorted order of DIST index of map-Table M)
END;
Time Complexity: O(nlogn) as there is n number of nodes and logn is the insertion time it takes
to insert in a map-table.

10.6.2 Step-wise explanation via diagrammatic approach


Note: The nodes at the same level and having the same horizontal distances, then in traversal,
anyone of the two will be written. As, if properly seen, both the nodes will overlap each other.
In the above figure, the left child of node C and right child of node B, i.e., E, will be at the same
level and distance; hence either of them will be considered in the traversal.

You might also like