Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Vertical Order Traversal
MEDIUM
35 mins
27 upvotes
Trees
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Trees
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Vertical Order Traversal

Contributed by
Shivam Kumar Singh
Medium
yellow-spark
0/80
Avg time to solve 35 mins
Success Rate 65 %
Share
27 upvotes

Problem Statement

Given a binary tree, return the vertical order traversal of the values of the nodes of the given tree.

For each node at position (X, Y), (X-1, Y-1) will be its left child position while (X+1, Y-1) will be the right child position.

Running a vertical line from X = -infinity to X = +infinity, now whenever this vertical line touches some nodes, we need to add those values of the nodes in order starting from top to bottom with the decreasing ‘Y’ coordinates.

Note:
If two nodes have the same position, then the value of the node that is added first will be the value that is on the left side.
For example:
For the binary tree in the image below.

alt text

The vertical order traversal will be {2, 7, 5, 2, 6, 5, 11, 4, 9}.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1:
2
1 2 3 4 -1 -1 -1 -1 -1
1 -1 2 -1 -1
Sample Output 1:
4 2 1 3 
1 2 
Explanation of Sample Input 1:
For the first test case, the vertical order traversal of the given binary tree will be {{4}, {2}, {1}, {3}}.

For the second test case, the vertical order traversal of the given binary tree will be {{1}, {2}}.
Sample Input 2:
2
2 1 -1 -1 -1
0 1 2 4 5 3 6 -1 -1 7 -1 -1 -1 -1 -1 -1 -1
Sample Output 2:
1 2
4 1 7 0 5 3 2 6 
Explanation of Sample Input 2:
For the first test case, the vertical order traversal of the given binary tree will be {{1}, {2}}.

For the second test case, the vertical order traversal of the given binary tree will be {{4}, {1, 7}, {0, 5, 3}, {2}, {6}}.
Reset Code
Full screen
Auto
copy-code
Console