#include <iostream> #include <iomanip> #include <queue> #include <deque> #include <conio.h> /* Print the level order of binary tree such that each level should print in a different line - start from the root - enqueue the node of that level - dequeue till queue is empty - add a new line - continue */ struct Node { Node(int x):data(x), left(0), right(0){} int data; Node* left, *right; }; std::queue<Node *> queue; Node* root = 0; void levelOrderTraversal() { queue.push(root); while(true) { std::queue<Node *> aux; while(!queue.empty()) { Node* tmp = queue.front(); std::cout << tmp->data << " "; if(tmp->left != NULL) aux.push(tmp->left); if(tmp->right != NULL) aux.push(tmp->right); queue.pop(); } std::cout << std::endl; queue = aux; if(queue.empty()) break; // end } } void spiralOrderTraversal() { queue.push(root); int rotate = 0; while(true) { std::queue<Node *> aux; std::deque<Node *> disp; // double ended queue while(!queue.empty()) { disp.push_back(queue.front()); Node* tmp = queue.front(); if(tmp->left != NULL) aux.push(tmp->left); if(tmp->right != NULL) aux.push(tmp->right); queue.pop(); } queue = aux; // display the contents of display queue while(!disp.empty()) { if(rotate) { std::cout << disp.back()->data << " "; disp.pop_back(); } else { std::cout << disp.front()->data << " "; disp.pop_front(); } } std::cout << std::endl; rotate = ~rotate; // change the direction if(queue.empty()) break; // end } } int main() { root = new Node(3); root->left = new Node(5); root->right = new Node(2); root->left->left = new Node(7); root->left->right = new Node(4); root->right->left = new Node(1); root->right->right = new Node(9); root->left->left->left = new Node(34); root->left->left->right = new Node(63); root->right->left->left = new Node(12); root->right->left->right = new Node(14); levelOrderTraversal(); spiralOrderTraversal(); getch(); }
Yet another blog from yet another software engineer - a collection of my thoughts and some snippets of code I write (mainly for my later reference). If you find this useful, lets discuss in comments.
December 19, 2012
Level and Spiral Order Traversal in CPP
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment