Print Binary Tree in 2-Dimensions

Given a Binary Tree, print it in two dimension.

Examples:

Input : Pointer to root of below tree
             1
            /  \
           2    3 
          / \   / \
         4   5  6  7 

Output :
                    7

          3

                    6

1

                    5

          2

                    4

We strongly recommend you to minimize your browser and try this yourself first.

If we take a closer look at the pattern, we can notice following.
1) Rightmost node is printed in first line and leftmost node is printed in last line.
2) Space count increases by a fixed amount at every level.

So we do a reverse inorder traversal (right – root – left) and print tree nodes. We increase space by a fixed amount at every level.



Below is the implementation.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to print binary tree in 2D 
#include<bits/stdc++.h> 
#include<iostream>
using namespace std; 
#define COUNT 10 
  
// A binary tree node 
class Node 
    public:
    int data; 
    Node* left, *right; 
      
    /* Constructor that allocates a new node with the 
    given data and NULL left and right pointers. */
    Node(int data){
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
}; 
  
// Function to print binary tree in 2D 
// It does reverse inorder traversal 
void print2DUtil(Node *root, int space) 
    // Base case 
    if (root == NULL) 
        return
  
    // Increase distance between levels 
    space += COUNT; 
  
    // Process right child first 
    print2DUtil(root->right, space); 
  
    // Print current node after space 
    // count 
    cout<<endl; 
    for (int i = COUNT; i < space; i++) 
        cout<<" "
    cout<<root->data<<"\n"
  
    // Process left child 
    print2DUtil(root->left, space); 
  
// Wrapper over print2DUtil() 
void print2D(Node *root) 
    // Pass initial space count as 0 
    print2DUtil(root, 0); 
  
// Driver code 
int main() 
    Node *root = new Node(1); 
    root->left = new Node(2); 
    root->right = new Node(3); 
  
    root->left->left = new Node(4); 
    root->left->right = new Node(5); 
    root->right->left = new Node(6); 
    root->right->right = new Node(7); 
  
    root->left->left->left = new Node(8); 
    root->left->left->right = new Node(9); 
    root->left->right->left = new Node(10); 
    root->left->right->right = new Node(11); 
    root->right->left->left = new Node(12); 
    root->right->left->right = new Node(13); 
    root->right->right->left = new Node(14); 
    root->right->right->right = new Node(15); 
      
    print2D(root); 
  
    return 0; 
  
// This code is contributed by rathbhupendra

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to print binary tree in 2D
#include<stdio.h>
#define COUNT 10
  
// A binary tree node
struct Node
{
    int data;
    Node* left, *right;
};
  
// Helper function to allocates a new node
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return node;
}
  
// Function to print binary tree in 2D
// It does reverse inorder traversal
void print2DUtil(Node *root, int space)
{
    // Base case
    if (root == NULL)
        return;
  
    // Increase distance between levels
    space += COUNT;
  
    // Process right child first
    print2DUtil(root->right, space);
  
    // Print current node after space
    // count
    printf("\n");
    for (int i = COUNT; i < space; i++)
        printf(" ");
    printf("%d\n", root->data);
  
    // Process left child
    print2DUtil(root->left, space);
}
  
// Wrapper over print2DUtil()
void print2D(Node *root)
{
   // Pass initial space count as 0
   print2DUtil(root, 0);
}
  
// Driver program to test above functions
int main()
    Node *root   = newNode(1);
    root->left   = newNode(2);
    root->right  = newNode(3);
  
    root->left->left  = newNode(4);
    root->left->right = newNode(5);
    root->right->left  = newNode(6);
    root->right->right = newNode(7);
  
    root->left->left->left  = newNode(8);
    root->left->left->right  = newNode(9);
    root->left->right->left  = newNode(10);
    root->left->right->right  = newNode(11);
    root->right->left->left  = newNode(12);
    root->right->left->right  = newNode(13);
    root->right->right->left  = newNode(14);
    root->right->right->right  = newNode(15); 
      
    print2D(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to print binary tree in 2D 
class GFG
{
      
static final int COUNT = 10
  
// A binary tree node 
static class Node 
    int data; 
    Node left, right; 
      
    /* Constructor that allocates a new node with the 
    given data and null left and right pointers. */
    Node(int data)
    
        this.data = data; 
        this.left = null
        this.right = null
    
}; 
  
// Function to print binary tree in 2D 
// It does reverse inorder traversal 
static void print2DUtil(Node root, int space) 
    // Base case 
    if (root == null
        return
  
    // Increase distance between levels 
    space += COUNT; 
  
    // Process right child first 
    print2DUtil(root.right, space); 
  
    // Print current node after space 
    // count 
    System.out.print("\n"); 
    for (int i = COUNT; i < space; i++) 
        System.out.print(" "); 
    System.out.print(root.data + "\n"); 
  
    // Process left child 
    print2DUtil(root.left, space); 
  
// Wrapper over print2DUtil() 
static void print2D(Node root) 
    // Pass initial space count as 0 
    print2DUtil(root, 0); 
  
// Driver code 
public static void main(String args[]) 
    Node root = new Node(1); 
    root.left = new Node(2); 
    root.right = new Node(3); 
  
    root.left.left = new Node(4); 
    root.left.right = new Node(5); 
    root.right.left = new Node(6); 
    root.right.right = new Node(7); 
  
    root.left.left.left = new Node(8); 
    root.left.left.right = new Node(9); 
    root.left.right.left = new Node(10); 
    root.left.right.right = new Node(11); 
    root.right.left.left = new Node(12); 
    root.right.left.right = new Node(13); 
    root.right.right.left = new Node(14); 
    root.right.right.right = new Node(15); 
      
    print2D(root); 
}
  
// This code is contributed by Arnab Kundu

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to print binary tree in 2D 
COUNT = [10
  
# Binary Tree Node 
""" utility that allocates a newNode 
with the given key """
class newNode: 
  
    # Construct to create a newNode 
    def __init__(self, key): 
        self.data = key
        self.left = None
        self.right = None
  
# Function to print binary tree in 2D 
# It does reverse inorder traversal 
def print2DUtil(root, space) :
  
    # Base case 
    if (root == None) :
        return
  
    # Increase distance between levels 
    space += COUNT[0]
  
    # Process right child first 
    print2DUtil(root.right, space) 
  
    # Print current node after space 
    # count 
    print() 
    for i in range(COUNT[0], space):
        print(end = " "
    print(root.data) 
  
    # Process left child 
    print2DUtil(root.left, space) 
  
# Wrapper over print2DUtil() 
def print2D(root) :
      
    # space=[0]
    # Pass initial space count as 0 
    print2DUtil(root, 0
  
# Driver Code 
if __name__ == '__main__':
  
    root = newNode(1
    root.left = newNode(2
    root.right = newNode(3
  
    root.left.left = newNode(4
    root.left.right = newNode(5
    root.right.left = newNode(6
    root.right.right = newNode(7
  
    root.left.left.left = newNode(8
    root.left.left.right = newNode(9
    root.left.right.left = newNode(10
    root.left.right.right = newNode(11
    root.right.left.left = newNode(12
    root.right.left.right = newNode(13
    root.right.right.left = newNode(14
    root.right.right.right = newNode(15
      
    print2D(root)
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

chevron_right


Output :


                              15

                    7

                              14

          3

                              13

                    6

                              12

1

                              11

                    5

                              10

          2

                              9

                    4

                              8

This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.