class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function verticalOrderTraversal(root: TreeNode | null): number[] {
if (!root) return [];
const columnTable = new Map<number, number[]>();
const queue: Array<[TreeNode, number]> = [[root, 0]];
let minColumn = 0, maxColumn = 0;
while (queue.length > 0) {
const [node, column] = queue.shift()!;
if (!columnTable.has(column)) {
columnTable.set(column, []);
}
columnTable.get(column)!.push(node.val);
if (node.left) {
queue.push([node.left, column - 1]);
minColumn = Math.min(minColumn, column - 1);
}
if (node.right) {
queue.push([node.right, column + 1]);
maxColumn = Math.max(maxColumn, column + 1);
}
}
const result: number[] = [];
for (let col = minColumn; col <= maxColumn; col++) {
if (columnTable.has(col)) {
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);
console.log(output.join(' -> '));const queue: Array<[TreeNode, number]> = [[root, 0]];
Initialize queue with root node at column 0
const [node, column] = queue.shift()!;
Dequeue node and its column for processing
if (!columnTable.has(column)) { columnTable.set(column, []); }
Create list for column if not exists
columnTable.get(column)!.push(node.val);
Add current node value to its column list
if (node.left) { queue.push([node.left, column - 1]); minColumn = Math.min(minColumn, column - 1); }
Add left child with column one less, update min column
if (node.right) { queue.push([node.right, column + 1]); maxColumn = Math.max(maxColumn, column + 1); }
Add right child with column one more, update max column
for (let col = minColumn; col <= maxColumn; col++) { if (columnTable.has(col)) { result.push(...columnTable.get(col)!); } }
Collect nodes from leftmost to rightmost column
4 -> 2 -> 1 -> 5 -> 3 -> 6