Update appNew update is available. Click here to update.

Boundary Traversal of Binary Tree

Contributed by
Prashansa
Last Updated: 23 Feb, 2023
Hard
yellow-spark
0/120
Avg time to solve 20 mins
Success Rate 85 %
Share
161 upvotes

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.

NOTE:
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. 
For Example:

alt text

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 10^2
1 <= N <= 2^12 

Where 'N' is the total number of nodes in the binary tree.

Time Limit: 1 sec
Sample Input 1:
2
1 2 3 4 -1 5 -1 -1 -1 -1 -1
1 2 -1 3 -1 4 -1 -1 -1
Sample Output 1:
1 2 4 5 3 
1 2 3 4
Explanation of Sample Input 1:
For the first 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.

For the second test case, we have 1 as the root node. 2, 3 as the left boundary nodes and 4 as a leaf node. We don't have any right boundaries.
Sample Input 2:
1
1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
Sample Output 2:
1 2 4 5 6 7 3  
Reset Code
Full screen
Auto
copy-code
Console