Level order traversal in spiral form

Complete the function to find spiral order traversal of a tree. For below tree, function should return 1, 2, 3, 4, 5, 6, 7.


 

Example 1:

Input:
      1
    /   \
   3     2
Output:1 3 2

Example 2:

Input:
           10
         /     \
        20     30
      /    \
    40     60
Output: 10 20 30 60 40 


Explanation: Characters in both the strings

are not same, so they are not anagrams.



c++ implementation:

void printSpiral(Node *root)
{  if (root == NULL) 
        return; 
  
    
    stack<struct Node*> s1;  
    stack<struct Node*> s2;  

    s1.push(root); 
  
     
    while (!s1.empty() || !s2.empty()) { 
        while (!s1.empty()) { 
            struct Node* temp = s1.top(); 
            s1.pop(); 
            cout << temp->data << " ";  
            if (temp->right) 
                s2.push(temp->right); 
            if (temp->left) 
                s2.push(temp->left); 
        } 
  
        while (!s2.empty()) { 
            struct Node* temp = s2.top(); 
            s2.pop(); 
            cout << temp->data << " "; 
            if (temp->left) 
                s1.push(temp->left); 
            if (temp->right) 
                s1.push(temp->right); 
        } 
    }

}



No comments

darkmode