Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

How to perform boundary traversal in binary tree using only single traversal of the tree?

I am doing it in this way (not a single traversal):

void printBoundary (struct node* root)
{
    if (root)
    {
        printf("%d ",root->data);

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

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

        // Print the right boundary in bottom-up manner
        if(root->right)
           printBoundaryRight(root->right);
        else
           printBoundaryRight(root->left);
    }
}
share|improve this question

1 Answer 1

I would check out http://www.fusu.us/2013/07/printing-binary-tree-boundary.html. It uses additional data structures but is but runs in linear time with a single traversal. The stacks used in the linked solution would not be necessary if you were not worried about the order in which the boundary is printed. In this case you could do your favorite linear tree traversal printing any node that satisfies the boundary condition (root or at least one child is null).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.