Given a Binary Tree, the task is to flatten it in order of ZigZag traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.
Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 2 5 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5
Approach: We will solve this problem by simulating the ZigZag traversal of Binary Tree.
- Create two stacks, “c_lev” and “n_lev” and to store the nodes of current and next level Binary tree.
- Create a variable “prev” and initialise it by parent node.
- Push right and left children of parent in the c_lev stack.
- Apply ZigZag traversal. Lets say “curr” is top most element in “c_lev”. Then,
- If ‘curr’ is NULL, continue.
- Else push curr->left and curr->right on the stack “n_lev” in appropriate order. If we are performing left to right traversal then curr->left is pushed first else curr->right is pushed first.
- Set prev = curr.
Below is the implementation of the above approach:
1 2 5 6 4 9 3
Time Complexity: O(N)
Space Complexity: O(N) where N is the size of Binary Tree.
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 post-order traversal
- Flatten Binary Tree in order of Level Order Traversal
- Level order traversal of Binary Tree using Morris Traversal
- Double Order Traversal of a Binary Tree
- Middle To Up-Down Order traversal of a Binary Tree
- Specific Level Order Traversal of Binary Tree
- Boundary Level order traversal of a Binary Tree
- Deletion of a given node K in a Binary Tree using Level Order Traversal
- Find the kth node in vertical order traversal of a Binary Tree
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Check if the level order traversal of a Binary Tree results in a palindrome
- Create a binary tree from post order traversal and leaf node array
- Build Binary Tree from BST such that it's level order traversal prints sorted data
- Flatten a binary tree into linked list
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Zig-Zag traversal of a Binary Tree using Recursion
- Sideways traversal of a Complete Binary Tree
- Clockwise Spiral Traversal of Binary Tree | Set - 2
- Clockwise Spiral Traversal of Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.