jain12

zig zag traversal in a binary tree

Mar 26th, 2020
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4.  
  5. class Node{
  6.   public:
  7.       int data;
  8.       Node *left,*right;
  9.       Node(int key){
  10.         data=key;
  11.         left=NULL;
  12.         right=NULL;
  13.         }
  14.   };
  15.  
  16. void ZigZagTraversal(Node* root){
  17.  if(root==NULL)
  18.     return;
  19.  stack<Node*>s1;
  20.  stack<Node*>s2;
  21.  s1.push(root);
  22.  while(!s1.empty()||!s2.empty()){
  23.     while(!s1.empty()){
  24.       Node *temp=s1.top();
  25.       cout<<" "<<temp->data;
  26.       s1.pop();
  27.       if(temp->left!=NULL)
  28.         s2.push(temp->left);
  29.       if(temp->right!=NULL)
  30.         s2.push(temp->right);
  31.       }
  32.     while(!s2.empty()){
  33.       Node *temp=s2.top();
  34.       cout<<" "<<temp->data;
  35.       s2.pop();
  36.       if(temp->right!=NULL)
  37.         s1.push(temp->right);
  38.       if(temp->left!=NULL)
  39.         s1.push(temp->left);
  40.       }
  41.     }
  42.  }
  43.  
  44. int main(){
  45.   Node* root=NULL;
  46.   Node* newnode=new Node(1);
  47.   root=newnode;
  48.   root->left=new Node(9);
  49.   root->right=new Node(3);
  50.   (root->left)->left=new Node(2);
  51.   (root->right)->left=new Node(8);
  52.   (root->right)->right=new Node(4);
  53.   ZigZagTraversal(root);
  54.   return 0;
  55.   }
Add Comment
Please, Sign In to add comment