Vertical Order Traversal Problem Statement

You are given a binary tree, and the task is to perform a vertical order traversal of the values of the nodes in the tree.

For a node at position ('X', 'Y'), the positions of its children are ('X'-1, 'Y'-1) for the left child and ('X'+1, 'Y'-1) for the right child.

A vertical line runs from X = -infinity to X = +infinity, adding node values it touches in order from top to bottom, based on decreasing 'Y' coordinates.

Input:

The first line contains an integer 'T', representing the number of test cases.
For each test case, a single line contains the level order traversal of the binary tree, with node values separated by a single space. Use -1 for null nodes.

Output:

For each test case, print the vertical order traversal of the binary tree, with node values separated by single spaces in a single line.

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
4 2 1 5 3 7 6

Constraints:

  • 1 <= 'T' <= 100
  • 0 <= 'N' <= 3000
  • 0 <= 'VAL' <= 105, where 'VAL' is a node's value
  • Time Limit: 1 sec
Note:

If two nodes have the same position, the node added first appears on the left. Implement the function without handling the printing, as it is managed in the testing framework.

AnswerBot
4mo

Perform vertical order traversal of a binary tree based on decreasing 'Y' coordinates.

  • Implement a function to perform vertical order traversal of a binary tree

  • Nodes are added in order from top to bott...read more

Help your peers!
Select
Add answer anonymously...

Top Lead Software Engineer Interview Questions Asked at Freshworks

Q. Given a string, find all palindromes within it.
Q. Elevator travel, find the no. of hops
Q. Given an array of integers, find all unique triplets (a, b, c) such that a + b +...read more
Lead Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits