Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST.
Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 2 3 4 5 6 7 8 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5
Approach: A simple approach will be to recreate the BST from its in-order traversal. This will take O(N) extra space were N is the number of node in BST.
To improve upon that, we will simulate in order traversal of a binary tree as follows:
- Create a dummy node.
- Create a variable called ‘prev’ and make it point to the dummy node.
- Perform in-order traversal and at each step.
- Set prev -> right = curr
- Set prev -> left = NULL
- Set prev = curr
This will improve the space complexity to O(H) in worst case as in-order traversal takes O(H) extra space.
Below is the implementation of the above approach:
2 3 4 5 6 7 8
- Flatten BST to sorted list | Decreasing order
- Flatten Binary Tree in order of Level Order Traversal
- Flatten binary tree in order of post-order traversal
- Flatten Binary Tree in order of Zig Zag traversal
- Flatten a binary tree into linked list | Set-2
- Flatten a binary tree into linked list | Set-3
- Flatten a binary tree into linked list
- Sort only non-prime numbers of an array in increasing order
- Print array elements in alternatively increasing and decreasing order
- Sorted order printing of a given array that represents a BST
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Check if value exists in level-order sorted complete binary tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Sorted Linked List to Balanced BST
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.