Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Level order traversal in spiral form

Write a function to print spiral order traversal of a tree.
For below tree, function should print 1, 2, 3, 7, 6, 5, 4.

           [1]
          /   \
       [2]     [3]
      /  \     /  \ 
    [4]  [5] [6]  [7]

Sort Stack in place

Question is to sort a Stack in place without using extra Stack or other Data Structure.

Answer :
Basic solution which comes in mind is to pop all element and sort and push into Stack again.
but as we don't have extra space or Data Structure to sort stack.
We need to use inplace sorting, and to do so we need to have all elements out of stack.
One way to do so is to use "Recursion" .
It will use internally memory stack to store recursion values. but we can implement without initializing extra stack or memory.