GeeksforGeeks » Interview Questions

Amazon Interview Question

(6 posts)
  • Started 9 months ago by tadivijaykumar
  • Latest reply from y2km11
  1. tadivijaykumar
    Member
    Posted 9 months ago #

    How can we print boundary nodes in a binary tree..?

  2. kapil
    guest
    Posted 9 months ago #

    What do you mean boundry nodes? Is it the leftmost and rightmost nodes at every level of tree?

  3. WgpShashank
    guest
    Posted 9 months ago #

    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

  4. srikantaggarwal
    Member
    Posted 6 months ago #

    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);
    }

  5. srikantaggarwal
    Member
    Posted 6 months ago #

    Sorry, while calling right tree use print_right_nodes(root->right);

  6. y2km11
    Member
    Posted 2 months ago #

    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.

RSS feed for this topic