patterncppMinor
Traversal of a tree in a top-view order
Viewed 0 times
ordertopviewtreetraversal
Problem
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.
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
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 -> 5 -> 3 -> 2 -> 7I 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->left);
coutdataright;//Don't want to print the root element twice
while(root != NULL)
{
coutdataright;
}
}
}Solution
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:
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.
static void top_view_post_order(node* root)
{
if (!root) return;
top_view_post_order(root->left);
cout data data right);
}
void top_view(node * root)
{
top_view_post_order(root);
top_view_pre_order(root->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.
Code Snippets
static void top_view_post_order(node* root)
{
if (!root) return;
top_view_post_order(root->left);
cout << root->data << " ";
}
static void top_view_pre_order(node* root)
{
if (!root) return;
cout << root->data << " ";
top_view_pre_order(root->right);
}
void top_view(node * root)
{
top_view_post_order(root);
top_view_pre_order(root->right);
}Context
StackExchange Code Review Q#105379, answer score: 3
Revisions (0)
No revisions yet.