Given a binary tree, print its nodes in vertical order. Assume that the left and right child of a node makes a 45–degree angle with the parent.

For example, nodes in vertical order for following binary tree is

2, 7
1, 5
3, 8
6

 
Vertical Traversal

Practice this problem

We have seen hash table implementation in the previous post, which takes O(n.log(n)) time for a binary tree with n nodes. We can improve the time complexity of the above solution to linear with an auxiliary data structure such as a doubly-linked list. The idea is to store the vertical order of the binary tree in a doubly-linked list, where each node of the doubly linked list stores every node corresponding to a vertical line in a binary tree. This post provides an overview of some available alternatives to accomplish this using a doubly-linked list.

1. Using Preorder traversal

We start by constructing a doubly linked list node that stores all nodes present at the vertical line passing through the root node. Then node->prev and node->next will correspond to nodes present at the vertical line passing through the root node’s left and right child, respectively. The trick is to recursively construct the linked list and add nodes to it as we traverse the tree using preorder traversal.

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

C++


Download  Run Code

Output:

2 7
1 5 9
3 8
10 6

Java


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[10, 6]

Python


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[10, 6]

2. Using Level Order Traversal

Since the above solution uses preorder traversal to traverse the tree, the nodes might not get processed in the same order as they appear in the binary tree from top to bottom. For instance, node 10 get printed before node 6 in the above solution.

We can perform a level order traversal to ensure that nodes are processed in the same order as they appear in the binary tree. The idea remains the same as the previous approach, except we traverse the binary tree using level order traversal instead of the preorder traversal. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

2 7
1 5 9
3 8
6 10

Java


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[6, 10]

Python


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[6, 10]

The time complexity of both above-discussed methods is O(n), where n is the total number of nodes in the binary tree. The auxiliary space used is O(n) for a doubly linked list.