//
// main.cpp
// Print Binary Tree Vertically
//
// Created by Himanshu on 25/09/21.
//
#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct node {
int value = 0;
struct node *left, *right;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->value = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
void printVertically (Node *root) {
if (root == NULL) {
return;
}
map<int, vector<int>> hmap;
map<int, vector<int>>::iterator it;
queue<pair<Node*, int>> qu;
int level = 0;
qu.push(make_pair(root, level));
while (!qu.empty()) {
int size = (int) qu.size();
for (int i=0; i<size; i++) {
pair<Node*, int> node = qu.front();
qu.pop();
Node *temp = node.first;
level = node.second;
hmap[level].push_back(temp->value);
if (temp->left) {
qu.push(make_pair(temp->left, level-1));
}
if (temp->right) {
qu.push(make_pair(temp->right, level+1));
}
}
level++;
}
for (it = hmap.begin(); it != hmap.end(); it++) {
for (int j = 0; j < it->second.size(); j++) {
cout << it->second[j] << " ";
}
cout << endl;
}
}
int main() {
Node *root = newNode(5);
root->left = newNode(3);
root->right = newNode(7);
root->left->left = newNode(2);
root->left->right = newNode(4);
root->left->left->right = newNode(1);
root->right->right = newNode(8);
cout<<"Vertical order:"<<endl;
printVertically (root);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBQcmludCBCaW5hcnkgVHJlZSBWZXJ0aWNhbGx5Ci8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDI1LzA5LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8cXVldWU+CiNpbmNsdWRlIDxtYXA+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpzdHJ1Y3Qgbm9kZSB7CiAgICBpbnQgdmFsdWUgPSAwOwogICAgc3RydWN0IG5vZGUgKmxlZnQsICpyaWdodDsKfTsKdHlwZWRlZiBzdHJ1Y3Qgbm9kZSBOb2RlOwoKbm9kZSogbmV3Tm9kZShpbnQgZGF0YSkKewogICAgbm9kZSogTm9kZSA9IG5ldyBub2RlKCk7CiAgICBOb2RlLT52YWx1ZSA9IGRhdGE7CiAgICBOb2RlLT5sZWZ0ID0gTlVMTDsKICAgIE5vZGUtPnJpZ2h0ID0gTlVMTDsKIAogICAgcmV0dXJuKE5vZGUpOwp9Cgp2b2lkIHByaW50VmVydGljYWxseSAoTm9kZSAqcm9vdCkgewogICAgaWYgKHJvb3QgPT0gTlVMTCkgewogICAgICAgIHJldHVybjsKICAgIH0KICAgIAogICAgbWFwPGludCwgdmVjdG9yPGludD4+IGhtYXA7CiAgICBtYXA8aW50LCB2ZWN0b3I8aW50Pj46Oml0ZXJhdG9yIGl0OwogICAgcXVldWU8cGFpcjxOb2RlKiwgaW50Pj4gcXU7CiAgICBpbnQgbGV2ZWwgPSAwOwogICAgCiAgICBxdS5wdXNoKG1ha2VfcGFpcihyb290LCBsZXZlbCkpOwogICAgCiAgICB3aGlsZSAoIXF1LmVtcHR5KCkpIHsKICAgICAgICBpbnQgc2l6ZSA9IChpbnQpIHF1LnNpemUoKTsKICAgICAgICBmb3IgKGludCBpPTA7IGk8c2l6ZTsgaSsrKSB7CiAgICAgICAgICAgIHBhaXI8Tm9kZSosIGludD4gbm9kZSA9IHF1LmZyb250KCk7CiAgICAgICAgICAgIHF1LnBvcCgpOwogICAgICAgICAgICBOb2RlICp0ZW1wID0gbm9kZS5maXJzdDsKICAgICAgICAgICAgbGV2ZWwgPSBub2RlLnNlY29uZDsKICAgICAgICAgICAgCiAgICAgICAgICAgIGhtYXBbbGV2ZWxdLnB1c2hfYmFjayh0ZW1wLT52YWx1ZSk7CiAgICAgICAgICAgIAogICAgICAgICAgICBpZiAodGVtcC0+bGVmdCkgewogICAgICAgICAgICAgICAgIHF1LnB1c2gobWFrZV9wYWlyKHRlbXAtPmxlZnQsIGxldmVsLTEpKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAodGVtcC0+cmlnaHQpIHsKICAgICAgICAgICAgICAgIHF1LnB1c2gobWFrZV9wYWlyKHRl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