Vertical Order Traversal of a Binary Tree

Try to solve the Vertical Order Traversal of a Binary Tree problem.

Statement#

Find the vertical order traversal of a binary tree when the root of the binary tree is given. In other words, return the values of the nodes from top to bottom in each column, column by column from left to right. If there is more than one node in the same column and row, return the values from left to right.

Constraints:

  • The number of nodes in the tree is in the range [1, 500].
  • 00 \leq Node.data 1000\leq 1000

Examples#

In the slides below, the input parameter is a list that represents the level order traversal of the binary tree.

canvasAnimation-image

1 of 3

canvasAnimation-image

2 of 3

canvasAnimation-image

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Vertical Order Traversal of a Binary Tree

1

What should be the output if the following tree is given as input?

tree = [25, 14, 35, -1, 15, null, 200, null, 10, null, null, 90, 350]

          __ 25 _ 
         |       |
      __ 14 _    35 _ 
     |       |       |
     -1 _    15   __ 200 _ 
         |       |        |
         10      90       350 
A)

[[25], [14, 35], [-1, 15, 200], [10, 90, 350]]

B)

[[-1], [14, 10], [25, 15], [35, 90], [200], [350]]

C)

[[-1], [14], [10], [25], [15], [35], [90], [200], [350]]

D)

[[25, 14, -1], [10], [14, 15], [200, 90], [125, 35, 200, 350]]

Question 1 of 20 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Traverse the tree, level by level, starting from the root node.

Push the nodes to a queue along with their column index.

If a node has children, assign column index current1current - 1 to the left child and current+1current + 1 to the right child.

Keep track of the maximum and minimum column indices, and populate a hash map with (index,node)(index, node) pairs.

Return the node values for each column index, from minimum to maximum.


Try it yourself#

Implement your solution in the following coding playground.

Python
usercode > main.py
Input #1
%0 node_1 100 node_2 50 node_1->node_2 node_3 200 node_1->node_3 node_4 25 node_2->node_4 node_5 75 node_2->node_5 node_8 350 node_4->node_8 node_9 15 node_4->node_9 node_6 300 node_3->node_6 node_7 10 node_3->node_7
Visualization for Input #1
Vertical Order Traversal of a Binary Tree

Solution: Symmetric Tree

Solution: Vertical Order Traversal of a Binary Tree