Vertical Order Traversal of a Binary Tree
Understand how to execute vertical order traversal on a binary tree by returning node values from top to bottom in each column, left to right. Explore strategies to handle nodes sharing the same row and column while practicing implementation in Go.
We'll cover the following...
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]. -
Node.data
Examples
In the slides below, the input parameter is an array that represents the level order traversal of the binary tree.
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
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
[[25], [14, 35], [-1, 15, 200], [10, 90, 350]]
[[-1], [14, 10], [25, 15], [35, 90], [200], [350]]
[[-1], [14], [10], [25], [15], [35], [90], [200], [350]]
[[25, 14, -1], [10], [14, 15], [200, 90], [125, 35, 200, 350]]
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.
Try it yourself
Implement your solution in main.go in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.
package mainimport (. "golang-test-code/ds_v1/BinaryTree") // TreeNode[T]func verticalOrder(root *TreeNode[int]) [][]int {// Replace this placeholder return statament with your codereturn make([][]int, 0)}