knakul853

Untitled

Jul 22nd, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1.  
  2. void printBottom(Node *node, int dist, int level, auto &map)
  3. {
  4.     // base case: empty tree
  5.     if (node == nullptr)
  6.         return;
  7.  
  8.     // if current level is more than or equal to maximum level seen so far
  9.     // for the same horizontal distance or horizontal distance is seen for
  10.     // the first time, update the map
  11.  
  12.     if (level >= map[dist].second)
  13.     {
  14.         // update value and level for current distance
  15.         map[dist] = { node->key, level };
  16.     }
  17.  
  18.     // recur for left subtree by decreasing horizontal distance and
  19.     // increasing level by 1
  20.     printBottom(node->left, dist - 1, level + 1, map);
  21.  
  22.     // recur for right subtree by increasing both level and
  23.     // horizontal distance by 1
  24.     printBottom(node->right, dist + 1, level + 1, map);
  25. }
  26.  
  27. // Function to print the bottom view of given binary tree
  28. void printBottom(Node *root)
  29. {
  30.     // create an empty map where
  31.     // key -> relative horizontal distance of the node from root node and
  32.     // value -> pair containing node's value and its level
  33.  
  34.     map<int, pair<int, int>> map;
  35.  
  36.     // do pre-order traversal of the tree and fill the map
  37.     printBottom(root, 0, 0, map);
  38.  
  39.     // traverse the map and print bottom view
  40.     for (auto it: map)
  41.         cout << it.second.first << " ";
  42. }
Add Comment
Please, Sign In to add comment