Complete the code to initialize the queue with the root node and its horizontal distance 0.
const queue: Array<[TreeNode, number]> = [];
queue.push([1]);We push a tuple with the root node and horizontal distance 0 to start the traversal.
Complete the code to update the map with the current node's value at its horizontal distance.
if (!map.has(hd)) { map.set(hd, []); } map.get(hd)!.[1](node.val);
We use push to add the node's value to the array at the horizontal distance.
Fix the error in the code that adds the left child to the queue with updated horizontal distance.
if (node.left) { queue.[1]([node.left, hd - 1]); }
We use push to add the left child at the end of the queue for BFS.
Fill both blanks to sort the keys and build the final vertical order array.
const sortedKeys = Array.from(map.keys()).[1]((a, b) => a [2] b); const result: number[][] = []; for (const key of sortedKeys) { result.push(map.get(key)!); }
We sort keys in ascending order using sort with comparator (a, b) => a - b.
Fill all three blanks to complete the vertical order traversal function.
function verticalOrder(root: TreeNode | null): number[][] {
if (!root) return [];
const map = new Map<number, number[]>();
const queue: Array<[TreeNode, number]> = [];
queue.push([1]);
while (queue.length > 0) {
const [node, hd] = queue.shift()!;
if (!map.has(hd)) {
map.set(hd, []);
}
map.get(hd)!.[2](node.val);
if (node.left) queue.push([node.left, hd [3] 1]);
if (node.right) queue.push([node.right, hd + 1]);
}
const sortedKeys = Array.from(map.keys()).sort((a, b) => a - b);
const result: number[][] = [];
for (const key of sortedKeys) {
result.push(map.get(key)!);
}
return result;
}The queue starts with [root, 0]. We push node values to the map arrays. The left child's horizontal distance is hd - 1.