25. Level order traversal in spiral form
The problem can be found at the following link: Question Link
My Approach
To determine the spiral order of a binary tree, I employ a queue to conduct a level-order traversal.
Starting from the root, I enqueue the elements of each level and subsequently process them individually. If left and right children exist, I enqueue them as well.
During the traversal of all levels, I store all the elements in the
out
vector.Additionally, I utilize the
turn
variable to check for alternate values(0 or 1, if 1 means reverse to form spiral), and if necessary(turn == 1), I'll reverse the corresponding subpart of the array.
Time and Auxiliary Space Complexity
Time Complexity: The algorithm visits each node once, and for each node, it performs constant time operations like pushing and popping from the queue. Thus, the time complexity is
O(N)
, whereN
is the number of nodes in the binary tree.Auxiliary Space Complexity:
O(W+N)
, whereN
is the number of nodes in the binary tree, andW
is the maximum width of the binary tree (the number of nodes in the level having the most nodes). In the worst case, the queue can store all the nodes of the last level.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated