top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to print the top view of an binary Tree?

0 votes
668 views
posted Jun 15, 2016 by Aditya Dwivedi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

The idea is to trace all the left element starting from root node and then print it in the bottom up manner using the function printLeft, and then print right element starting from root node in top down manner, to avoid printing of root node twice I have used flag. Here is the function:

void printLeft(node *p){
    if(p){
        printLeft(p->left);
        cout<< p->data << ' ';
    }
}
void printRight(node *p){
    static int flag=1;
    if(p){
        if(flag!=1)
          cout<< p->data << ' ';
        flag++;
        printRight(p->right);

    }
}
void top_view(node * root)
{
  printLeft(root);
  printRight(root);
}
answer Jun 15, 2016 by Shahsikant Dwivedi
Similar Questions
+6 votes

Given binary tree is:

        1
     /     \
    2        3
  /  \        \
 4   5         6
             /   \
            7     8

The output should be 1, 2, 3, 4, 5, 6, 7, 8

+4 votes

Given binary tree is:

            1
         /     \
        2        3
      /  \        \
     4   5         6
                 /   \
                7     8

The output will be 7,8,4,5,6,2,3,1

+2 votes

Given Tree

          6
       /     \
     7        8
   /   \     /  \
  9    10  11    12
                  \
                   13

Expected Output
6 8 12 13

...