Dsa Assignment No 5
Dsa Assignment No 5
Title:
Convert given binary tree into threaded binary tree. Analyze time and space complexity of the
algorithm.
Learning Objective:
To understand the basic concept of Non-Linear Data Structure “threaded binary tree” and its use
in Data structure.
Learning Outcome:
To convert the Binary Tree into threaded binary tree and analyze its time and space complexity.
Theory –
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without
recursion.
In a simple threaded binary tree, the NULL right pointers are used to store inorder successor.
Wherever a right pointer is NULL, it is used to store inorder successor.
Inorder traversal of a Binary tree is either be done using recursion or with the use of a auxiliary stack.
1) Single Threaded:
Where a NULL right pointer is made to point to the inorder successor Following diagram shows an
example Single Threaded Binary Tree. The dotted lines represent threads.
Inorder Traversal = 4 2 5 1 6 3 7
1 -999 0
1 1 0
1 3 1
1 2 1
0 4 0 0 5 0 0 6 0 0 7 0
2 ) Double Threaded:
Where both left and right NULL pointers are made to point to inorder predecessor and inorder
successor, respectively. The predecessor threads are useful for reverse inorder traversal and
postorder traversal.
The threads are also useful for fast accessing ancestors of a node.
1 -999 0
1 1 0
1 3 1
1 2 1
0 4 0 0 5 0 0 6 0 0 7 0
struct Node
{
int data;
Node *left, *right;
bool lbit, rbit;
}
● Traversing the binary tree to thread the nodes takes O(n) time, where n is the number of nodes in the tree.
● Finding the leftmost and rightmost nodes takes O(n) time in total.
● Overall, the time complexity of the algorithm is O(n).
● The space complexity primarily depends on the recursion stack during in-order traversal, which could be
O(h), where h is the height of the tree. In the worst case (for skewed trees), it could be O(n).
● Additionally, the algorithm uses a constant amount of extra space for auxiliary variables.
● Thus, the overall space complexity is O(n).
Expected Outcome:
The binary tree into threaded binary tree in one single traversal with no extra space required.
Conclusion: Able to convert the Binary Tree into threaded binary tree and analyze its time and
space complexity.