Skip to content

Instantly share code, notes, and snippets.

@dheshanm
Created February 22, 2018 17:49
Show Gist options
  • Save dheshanm/29a5c0ec410074f6b44525888dcd3fcf to your computer and use it in GitHub Desktop.
Save dheshanm/29a5c0ec410074f6b44525888dcd3fcf to your computer and use it in GitHub Desktop.
Display Binary Tree
void displayTree(Node * root) {
std::vector<Node*> GlobalStack;
GlobalStack.push_back(root);
int emptyLeaf = 32;
bool isRowEmpty = false;
std::cout << "****......................................................****";
while (!isRowEmpty) {
std::vector<Node*> LocalStack;
isRowEmpty = true;
for (int j=0; j<emptyLeaf; j++) {
std::cout << " ";
}
while (!GlobalStack.empty()) {
Node* temp = GlobalStack.pop_back();
if(temp != nullptr) {
std::cout << temp->data;
LocalStack.push_back(temp->left);
LocalStack.push_back(temp->right);
if(temp->left != nullptr || temp->right!= nullptr) {
isRowEmpty = false;
}
else {
std::cout << "--";
LocalStack.push_back(nullptr);
LocalStack.push_back(nullptr);
}
for (int j=0; j<emptyLeaf*2-2; j++) {
std::cout << " ";
}
}
std::cout << std::endl;
emptyLeaf /= 2;
while (!LocalStack.empty()) {
GlobalStack.push_back(LocalStack.pop_back());
}
}
}
std::cout << "****......................................................****";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment