Good evening! Here's our prompt for today.
Vertical Order Traversal of a Binary Tree
What is Vertical Order Traversal?
In a binary tree, each node has a position defined by its (row, col)
coordinates. The vertical order traversal
is a method of visiting all the nodes in the tree column-by-column, starting from the leftmost to the rightmost columns. In this traversal, for each column, you will go from the top node to the bottom node.
Imagine the tree as a grid. The root node sits at (0, 0)
and as you move down the tree, the row number increases. When you go left, the column number decreases, and when you go right, the column number increases.

Sorting Nodes in the Same Column
Sometimes, you'll find multiple nodes in the same row and column. When this happens, you should sort these nodes based on their values, in ascending order.
Coordinates of Child Nodes
For any node at (row, col)
, its children will be positioned as follows:
- The left child will be at
(row + 1, col - 1)
- The right child will be at
(row + 1, col + 1)
Constraints
- The tree will have between 1 and 1000 nodes.
- The value of each node will be in the range
[0, 1000]
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
console.log('PASSED: ' + "columnNodesBinaryTree([7, 10, 9, null, 11, null, null, null, 12]) should return `[[10], [7, 11], [9, 12]]`");
var assert = require('assert');
​
function TreeNode(val) {
this.val = val
this.left = null
this.right = null
}
​
function columnNodesBinaryTree(root) {
// add your code here
return;
}
​
try {
let root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
assert.deepEqual(columnNodesBinaryTree(root), [
[9],
[3, 15],
[20],
[7]
]);
​
console.log('PASSED: ' + "columnNodesBinaryTree([3, 9, 20, null, null, 15, 7]) should return `[[9], [3, 15], [20], [7]]`");
} catch (err) {
console.log(err);
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.