Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print the bottom view of a given binary tree
- #include <iostream>
- #include <queue>
- #include <map>
- 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 bottom view of the binary tree
- void bottom_view(node *root){
- if(root == NULL){
- return;
- }
- // we keep track of the horizontal distance of the node from the root node
- // to print the bottom view
- int hd = 0; // hd = horizontal distance from the root node
- hd = root->hd;
- // creating a Queue for storing node for level wise traversal
- // and a map for mapping horizontal distances with the node data
- queue<node *> Q;
- map<int, int> Map;
- Q.push(root);
- while(!Q.empty()){
- // pop the first node from the queue
- node *p = Q.front();
- Q.pop();
- hd = p->hd;
- Map[hd] = p->data;
- // increase the horizontal distance from the root node in negative direction
- // and push the node on queue
- if(p->left != NULL){
- p->left->hd = hd - 1;
- Q.push(p->left);
- }
- // increase the horizontal distance from the root node in positive direction
- // and push the node on queue
- if(p->right != NULL){
- p->right->hd = hd + 1;
- Q.push(p->right);
- }
- }
- // print the generated map
- cout<<"Bottom view of the binary tree is : "<<endl;
- for (auto iter = Map.begin(); iter != Map.end(); iter++){
- cout<<iter->second <<" ";
- }
- }
- 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;
- bottom_view(head);
- return 0;
- }
Add Comment
Please, Sign In to add comment