Boundary Traversal — Asked in Microsoft, eBay and Morgan Stanley

Problem Statement :

You have been given a binary tree of integers. Your task is to print the boundary nodes of this binary tree in Anti-Clockwise direction starting from the root node.

The boundary nodes of a binary tree include nodes from the left boundary, right boundary and the leaf nodes without duplicate nodes. However, the values from the nodes may contain duplicates.

The only line of each test case contains elements in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 on its place.

Sample Input:

Sample Output:

Explanation of Sample Test Case:

We have 1 as the root node. 2, 4 as left boundary nodes. 3, 5 as the right boundary nodes. We don’t have any leaf nodes.

Approach :

Recursion Based Approach

The boundary traversal of a binary tree can be broken down into 4 parts. These parts are given in the same order as they are present in the traversal-

  1. The root node — The root node will always be our first node in the whole boundary traversal.
  2. The left boundary — The left most nodes of the left subtree are also included in the boundary traversal, so we will process them next except for the leaf node as it will be processed in our next part. We can use recursion for this and traverse for only left child until a leaf node is encountered. If the left child is not present we recurse for the right child.
  3. The leaf Nodes — The leaf nodes of the binary tree will be processed next. We can use a simple inorder traversal for that. Inorder traversal will make sure that we process leaf nodes from left to right.
  4. The right boundary — The right most nodes of the right subtree will be processed at last in reverse order except for the leaf node as it is already processed in the previous part. For this, we can use recursion in a postorder manner and traverse for the right child only until we encounter a leaf node. If the right child is not present we will recurse for the left child. The postorder recursion will make sure that we traverse the right boundary in reverse order.

Time Complexity : O(N)
Space Complexity : O(N)

Code :

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store