Given a binary tree, perform the boundary traversal on it.

The solution should print the boundary nodes starting from the tree’s root, in an anti-clockwise direction, without any duplicates. For example, the following binary tree’s boundary traversal is 1, 2, 4, 8, 12, 13, 10, 6, 14, 11, 7, 3:

Binary Tree

Practice this problem

The idea is to split the problem into 3 parts:

  • Print the left boundary in a top-down fashion.
  • Print the leaf nodes in the same order as in the inorder traversal.
  • Print the right boundary in a bottom-up fashion.

This approach looks simple, but there are several edge cases the solution should handle to avoid printing duplicates:

  • Both the left boundary and the right boundary traversal prints the root node. We can avoid this by printing the root node first and performing the left boundary traversal on the root’s left child and the right boundary traversal on the root’s right child.
  • The leftmost and the rightmost node of the binary tree are leaf nodes. They will get printed while performing the left boundary and the right boundary traversal while printing the leaf nodes. To avoid it, exclude the leaf nodes while doing the left boundary and the right boundary traversal.

Following is the pictorial representation of the above logic:

Boundary Traversal of Binary Tree

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 2 4 8 12 13 10 6 14 11 7 3

Java


Download  Run Code

Output:

1 2 4 8 12 13 10 6 14 11 7 3

Python


Download  Run Code

Output:

1 2 4 8 12 13 10 6 14 11 7 3

The time complexity of the above solution is O(n), where n is the total number of nodes in the tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.