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.
1 2 3 4 -1 5 -1 -1 -1 -1 -1
1 2 4 5 3
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.
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-
- The root node — The root node will always be our first node in the whole boundary traversal.
- 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.
- 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.
- 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)