class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function verticalOrderTraversal(root) {
if (!root) return [];
const columnTable = new Map();
const queue = [];
queue.push([root, 0]); // node with its column index
while (queue.length > 0) {
const [node, col] = queue.shift();
if (!columnTable.has(col)) {
columnTable.set(col, []);
}
columnTable.get(col).push(node.val); // add node value to its column
if (node.left) {
queue.push([node.left, col - 1]); // left child column is col-1
}
if (node.right) {
queue.push([node.right, col + 1]); // right child column is col+1
}
}
const sortedCols = Array.from(columnTable.keys()).sort((a, b) => a - b);
const result = [];
for (const col of sortedCols) {
result.push(columnTable.get(col));
}
return result;
}
// Driver code
const root = new TreeNode(1,
new TreeNode(2,
new TreeNode(4),
new TreeNode(5)
),
new TreeNode(3,
null,
new TreeNode(6)
)
);
const output = verticalOrderTraversal(root);
for (const colNodes of output) {
console.log(colNodes.join(' -> '));
}queue.push([root, 0]); // node with its column index
Initialize queue with root node at column 0
const [node, col] = queue.shift();
Take next node and its column from queue for processing
if (!columnTable.has(col)) { columnTable.set(col, []); }
Create list for column if not exists
columnTable.get(col).push(node.val); // add node value to its column
Add current node value to its column group
if (node.left) { queue.push([node.left, col - 1]); }
Add left child to queue with column one less
if (node.right) { queue.push([node.right, col + 1]); }
Add right child to queue with column one more
const sortedCols = Array.from(columnTable.keys()).sort((a, b) => a - b);
Sort columns from left to right
for (const col of sortedCols) { result.push(columnTable.get(col)); }
Collect node groups in column order