Traversal of a tree in a top-view order I was trying to solve this problem.


  Problem Statement
  
  You are given a pointer to the root of a binary tree. Print the top
  view of the binary tree.  You only have to complete the function.


For example :

     3
   /   \
  5     2
 / \   / \
1   4 6   7
 \       /
  9     8
Top View : 1 -&gt; 5 -&gt; 3 -&gt; 2 -&gt; 7


I figured that the answer could be obtained by keeping on going till the leftmost node recursively and then traverse the tree till the rightmost node from the root.

Although I have managed to solve this problem I feel that my solution is just a little hack and not the best possible solution. The function I had written is 

/*
struct node
{
    int data;
    node* left;
    node* right;
};

*/
void top_view(node * root)
{
   static node* temp = root;
   if(root == NULL)
    {
    return;
   }
   top_view(root-&gt;left);
   cout&lt;&lt;root-&gt;data&lt;&lt;" ";
   if(root == temp)
      {
      root = root-&gt;right;//Don't want to print the root element twice
      while(root != NULL)
         {
         cout&lt;&lt;root-&gt;data&lt;&lt;" ";
         root = root-&gt;right;
      }
   } 
}
You can define two helper functions: one traverses the leftmost branch using post-order and another one traverses the rightmost branch using pre-order. See what I mean:

static void top_view_post_order(node* root)
{
    if (!root) return;

    top_view_post_order(root-&gt;left);
    cout &lt;&lt; root-&gt;data &lt;&lt; " ";
}

static void top_view_pre_order(node* root)
{
    if (!root) return;

    cout &lt;&lt; root-&gt;data &lt;&lt; " ";
    top_view_pre_order(root-&gt;right);
}

void top_view(node * root)
{
    top_view_post_order(root);
    top_view_pre_order(root-&gt;right);
}


The above passed the hackerrank's test.

Edit: What comes to static fields in functions, most books suggest that their presence is an indicator of a design flaw; don't do them - pass some structure to the function as "state information". Also, if you were to write multithreaded code, there is a great potential for data races as well.