Traversal of a tree in a top-view order
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.