Given a binary tree, print all nodes for each diagonal having negative slope (\). Assume that the left and right child of a node makes a 45–degree angle with the parent.

For example, consider the following binary tree having three diagonals. The diagonal’s traversal is:

1 3 6
2 5 8
4 7

Diagonal Traversal of Binary Tree

Practice this problem

Recursive Version

We can easily solve this problem with the help of hashing. The idea is to create an empty map where each key in the map represents a diagonal in the binary tree, and its value maintains all nodes present in the diagonal. Then perform preorder traversal on the tree and update the map. For each node, recur for its left subtree by increasing the diagonal by one and recur for the right subtree with the same diagonal.

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

C++


Download  Run Code

Output:

1 3 6
2 5 8
4 7

Java


Download  Run Code

Output:

[1, 3, 6]
[2, 5, 8]
[4, 7]

Python


Download  Run Code

Output:

[1, 3, 6]
[2, 5, 8]
[4, 7]

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.

Iterative Version

We can also use a queue to solve this problem. The idea is similar to level order traversal, but instead of storing nodes of a level, we enqueue nodes in a diagonal.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 3 6
2 5 8
4 7

Java


Download  Run Code

Output:

1 3 6
2 5 8
4 7

Python


Download  Run Code

Output:

1 3 6
2 5 8
4 7

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.

 
Exercise: Modify the solution to print diagonal elements for diagonals having positive slope /.