Given a binary tree, print corner nodes of every level in it.

For example, consider the following tree:

Print Corner Nodes


Output:
 
6
3 8
4 2
1 3

Practice this problem

The idea is simple. First, modify the level order traversal on a given binary tree to maintain the level of each node. Then while doing level order traversal, if the current node happens to be the first or last node at the current level, print it.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

1
2 3
4 6
7 10

Java


Download  Run Code

Output:

1
2 3
4 6
7 10

Python


Download  Run Code

Output:

1
2 3
4 6
7 10

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.