top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Print Border of given Tree in Anticlockwise Direction ?

+7 votes
389 views
     50
    /  \
   20   30
   / \
  70  80
 /  \   \
10   40  60        

printing the border elements anticlockwise direction:
->50->20->70->10->40->60->30

posted Nov 23, 2013 by Diya Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
// A function to print all left boundary nodes, except a leaf node and print the nodes in TOP DOWN manner
void printBoundaryLeft(struct node* root)
{
    if (root)
    {
        if (root->left)
        {
            // to ensure top down order, print the node
            // before calling itself for left subtree
            printf("%d ", root->data);
            printBoundaryLeft(root->left);
        }
        else if( root->right )
        {
            printf("%d ", root->data);
            printBoundaryLeft(root->right);
        }
        // do nothing if it is a leaf node, this way we avoid
        // duplicates in output
    }
}



// A function to print all right boundary nodes, except a leaf node. Print the nodes in BOTTOM UP manner
void printBoundaryRight(struct node* root)
{
    if (root)
    {
        if ( root->right )
        {
            // to ensure bottom up order, first call for right
            //  subtree, then print this node
            printBoundaryRight(root->right);
            printf("%d ", root->data);
        }
        else if ( root->left )
        {
            printBoundaryRight(root->left);
            printf("%d ", root->data);
        }
       // do nothing if it is a leaf node, this way we avoid
       // duplicates in output
    }
}

// A function to do boundary traversal of a given binary tree
void printBoundary (struct node* root)
{
    if (root)
    {
        printf("%d ",root->data);

        // Print the left boundary in top-down manner.
        printBoundaryLeft(root->left);

        // Print all leaf nodes
        printLeaves(root->left);
        printLeaves(root->right);

        // Print the right boundary in bottom-up manner
        printBoundaryRight(root->right);
    }
}
answer Nov 23, 2013 by Jai Prakash
Please tell the complexity ??
Similar Questions
+7 votes

Print cousins of a given node (Not sibling) ??

+6 votes
The input tree is as shown below
            40
            / \
        20      60
        / \       \
    10      30      80
      \            /  \ 
       15        70    90

Output: 15 30 60 80 90
...