Print view of Binary tree
Views of a binary tree, such as top view, bottom view, left view, and right view, refer to the set of nodes visible when the tree is looked at from specific directions. Each view provides a different perspective on the tree.
Table of Contents
Print left view of binary tree
void printLeftView(Node* root)
{
if (!root)
return;
queue<Node*> q;
q.push(root);
while (!q.empty())
{
// number of nodes at current level
int n = q.size();
// Traverse all nodes of current level
for(int i = 1; i <= n; i++)
{
Node* temp = q.front();
q.pop();
// Print the left most element
// at the level
if (i == 1)
cout<<temp->data<<" ";
// Add left node to queue
if (temp->left != NULL)
q.push(temp->left);
// Add right node to queue
if (temp->right != NULL)
q.push(temp->right);
}
}
}
Print Right View of Binary Tree
void printRightView(Node* root)
{
if (root == NULL)
return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
// get number of nodes for each level
int n = q.size();
// traverse all the nodes of the current level
while (n--) {
Node* x = q.front();
q.pop();
// print the last node of each level
if (n == 0) {
cout << x->data << " ";
}
// if left child is not null push it into the
// queue
if (x->left)
q.push(x->left);
// if right child is not null push it into the
// queue
if (x->right)
q.push(x->right);
}
}
}
Print Top View of Binary Tree
void topView(Node* root) {
if (!root)
return;
std::map<int, int> topViewMap;
std::queue<std::pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
Node* current = q.front().first;
int horizontalDistance = q.front().second;
q.pop();
if (topViewMap.find(horizontalDistance) == topViewMap.end()) {
topViewMap[horizontalDistance] = current->data;
}
if (current->left) {
q.push({current->left, horizontalDistance - 1});
}
if (current->right) {
q.push({current->right, horizontalDistance + 1});
}
}
for (const auto& entry : topViewMap) {
std::cout << entry.second << " ";
}
std::cout << std::endl;
}
Print Bottom View of Binary Tree
void bottomView(Node* root) {
if (!root)
return;
std::map<int, int> bottomViewMap;
std::queue<std::pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
Node* current = q.front().first;
int horizontalDistance = q.front().second;
q.pop();
bottomViewMap[horizontalDistance] = current->data;
if (current->left) {
q.push({current->left, horizontalDistance - 1});
}
if (current->right) {
q.push({current->right, horizontalDistance + 1});
}
}
for (const auto& entry : bottomViewMap) {
std::cout << entry.second << " ";
}
std::cout << std::endl;
}