GeeksforGeeks » Interview Questions
Amazon Interview Question
(6 posts)-
How can we print boundary nodes in a binary tree..?
-
What do you mean boundry nodes? Is it the leftmost and rightmost nodes at every level of tree?
-
If i am getting question correct i tried it sometimes back you might be interested in this.
http://shashank7s.blogspot.com/2011/03/wap-print-edge-nodes-boundary-of-binary.html
do notify me if i missed anything
Shashank
-
Hi,
We can do this by making following traversals:
print_left_nodes(root);
print_lower_nodes(root);
print_right_nodes(root);print_left_nodes(node root)
{
if(root == NULL)
return;
else
{
printf("%d", root->value);
get_left_nodes(root->left);
}
}print_lower_nodes(node root)
{
if((root->left == NULL) && (root->right) == NULL))
printf("%d",root->value);
else
{
if(root->left != NULL)
print_lower_nodes(root->left);
if(root->right != NULL)
print_lower_nodes(root->right);
}
}print_right_nodes(root node)
{
if(root == NULL)
return;
else
{
printf("%d", node->right);
print_right_nodes(node->right);
}
}Another method is by using
void print_boundary_nodes(node root, int index, int depth)
{
if(((root->left) == NULL) && ((root->right)==NULL))
{
printf("%d", root->value);
return;
}
else
{
if(index == pow(2,depth))
{
printf("%d", root->value);
}
else if(index == (pow(2, depth+1) -1))
{
printf("%d", root->value);
}
if(root->left != NULL)
print_boundary_nodes(root->left, 2*index, depth+1);
if(root->right != NULL)
print_boundary_nodes(root->right, 2*index+1, depth+1);
} -
Sorry, while calling right tree use print_right_nodes(root->right);
-
You have to print the left and right most nodes in each level. So a breadth first traversal would suffice. To track the starting and ending of each level use a dummy node in the queue.
Reply
You must log in to post.