Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // Program to print the given binary tree in a spiral order level wise traversal
- #include <iostream>
- #include <stack>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->hd = -1;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to print the tree using spiral level wise traversal
- void spiral_traversal(node* root){
- if (root == NULL){
- return;
- }
- stack<node *> STACK1, STACK2;
- int level = 1;
- STACK1.push(root);
- while(!STACK1.empty() || !STACK2.empty()){
- cout<<"\nNodes at level "<<level<<" are : ";
- level += 1;
- while (!STACK1.empty()){
- // pop the first node from the queue
- node *NODE = STACK1.top();
- STACK1.pop();
- cout<<NODE->data<<" ";
- // push the left child on queue
- if (NODE->right != NULL) {
- STACK2.push(NODE->right);
- }
- // push the right child on queue
- if (NODE->left != NULL) {
- STACK2.push(NODE->left);
- }
- }
- cout<<"\nNodes at level "<<level<<" are : ";
- level += 1;
- while (!STACK2.empty()){
- // pop the first node from the queue
- node *NODE = STACK2.top();
- STACK2.pop();
- cout<<NODE->data<<" ";
- // push the left child on queue
- if (NODE->right != NULL) {
- STACK1.push(NODE->right);
- }
- // push the right child on queue
- if (NODE->left != NULL) {
- STACK1.push(NODE->left);
- }
- }
- }
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- cout<<"SPIRAL Level wise traversal of the above binary tree is : "<<endl;
- spiral_traversal(head);
- }
Add Comment
Please, Sign In to add comment