Given a binary tree, the task is to flatten it in order of its post-order traversal. In the flattened binary tree, the left node of all the nodes must be NULL.
Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 2 4 3 6 8 7 5 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 5 4 3 2 1
A simple approach will be to recreate the Binary Tree from its post-order traversal. This will take O(N) extra space were N is the number of nodes in BST.
A better solution is to simulate post-order traversal of the given binary tree.
- Create a dummy node.
- Create variable called ‘prev’ and make it point to the dummy node.
- Perform post-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 the worst case as post-order traversal takes O(H) extra space.
Below is the implementation of the above approach:
2 4 3 6 8 7 5
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Flatten Binary Tree in order of Level Order Traversal
- Flatten Binary Tree in order of Zig Zag traversal
- Find postorder traversal of BST from preorder traversal
- Level order traversal of Binary Tree using Morris Traversal
- Postorder traversal of Binary Tree without recursion and without stack
- Find n-th node in Postorder traversal of a Binary Tree
- Find parent of given node in a Binary Tree with given postorder traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Iterative Postorder Traversal of N-ary Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Insertion in n-ary tree in given order and Level order traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Print Postorder traversal from given Inorder and Preorder traversals
- Iterative Postorder traversal | Set 3
- Flatten a binary tree into linked list
- Flatten a binary tree into linked list | Set-2
- Flatten a binary tree into linked list | Set-3
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.