![]() |
VOOZH | about |
Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.
Examples:
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level order traversal, keep track of previous node. Make current node as right child of previous and left of previous node as NULL. This solution requires queue, but question asks to solve without additional data structure.
Efficient Without Additional Data Structure Recursively look for the node with no grandchildren and both left and right child in the left sub-tree. Then store node->right in temp and make node->right=node->left. Insert temp in first node NULL on right of node by node=node->right. Repeat until it is converted to linked list. Even though this approach does not require additional data structure , but still it takes space for Recursion stack.
For Example,
Implementation:
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Complexity Analysis:
Another Approach:
We will use the intuition behind Morris’s traversal. In Morris Traversal we use the concept of a threaded binary tree.
Implementation:
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Time Complexity: O(N) Time complexity will be the same as that of a Morris's traversal
Auxiliary Space: O(1)
Another Approach Using Stack:
In this solution, we start by initializing a prev variable to None. This variable will keep track of the previously flattened node as we recursively flatten the binary tree.
This algorithm flattens the binary tree in pre-order traversal, so the resulting "linked list" will be in the same order as a pre-order traversal of the tree.
Implementation:
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Time Complexity: O(N), The loop will execute for every node once.
Space Complexity: O(N), Auxiliary Stack Space is needed.