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); }
Given binary tree is:
1 / \ 2 3 / \ \ 4 5 6 / \ 7 8
The output should be 1, 2, 3, 4, 5, 6, 7, 8
The output will be 7,8,4,5,6,2,3,1
Given Tree
6 / \ 7 8 / \ / \ 9 10 11 12 \ 13
Expected Output 6 8 12 13