Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to print the nodes of a binary tree in vertical order
- #include <iostream>
- #include <queue>
- #include <map>
- #include <list>
- #include <stack>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- int hd;
- 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 nodes of the binary tree in vertical order
- // using horizontal distance of a node from the root node
- void vertical_order(node* root){
- if(root == NULL){
- return;
- }
- // initialize a map and queue
- // we will use iterative BFS traversal to solve this
- map<int, vector<int> > M;
- queue<node *> Q;
- // push root in queue and initialize horizontal distance
- Q.push(root);
- int horizontal_distance = root->hd;
- while(!Q.empty()){
- node* current = Q.front();
- Q.pop();
- M[current->hd].push_back(current->data);
- // update horizontal distance of the left child and put it in the queue
- if(current->left != NULL){
- current->left->hd = current->hd - 1;
- Q.push(current->left);
- }
- // update horizontal distance of the right child and put it in the queue
- if(current->right != NULL) {
- current->right->hd = current->hd + 1;
- Q.push(current->right);
- }
- }
- // printing the contents of the map
- for (auto iter = M.begin(); iter != M.end(); iter++){
- vector<int> simple = iter->second;
- cout<<"vertical distance = "<<iter->first<<" elements : ";
- for(auto i=0; i != simple.size(); i++){
- cout<<simple[i]<<" ";
- }
- cout<<"\n";
- }
- }
- 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);
- head->hd = 0;
- vertical_order(head);
- }
- /*
- vertical distance = -3 elements : 10
- vertical distance = -2 elements : 4 9
- vertical distance = -1 elements : 2 7
- vertical distance = 0 elements : 1 5
- vertical distance = 1 elements : 3 8
- vertical distance = 2 elements : 6 11
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment