Leet Code Solution 987 - Vertical Order Traversal of a Binary Tree

Updated on

DISCLAIMER: Expressed views on this blog are my own.

987. Vertical Order Traversal of a Binary Tree, Hard

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.


For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).


The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.


Return the vertical order traversal of the binary tree.

Solution, Typescript

/**
* Definition for a binary tree node.
* 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 verticalTraversal(root: TreeNode | null): number[][] {
let result = [];
let resultStartCol = 0;

let row = 0, col = 0;
let rootCell = createCell(root, 0, 0);
let stack = [rootCell];

while(stack.length > 0) {
let cell = stack.shift();
let node = cell.node;

if(node.left) {
stack.push(createCell(node.left, cell.x+1, cell.y-1));
}

if(node.right) {
stack.push(createCell(node.right, cell.x+1, cell.y+1));
}

if(resultStartCol > cell.y) {
resultStartCol = cell.y;
result.unshift([]);
}
let idx = cell.y - resultStartCol;
if(result.length < idx + 1) {
if(cell.y >= 0) {
result[idx] = [];
}
}
// console.log(idx, cell.x, cell.y, resultStartCol, result.length);
result[idx].push(cell);
}
for(let idx = 0; idx < result.length; idx++) {

result[idx].sort((a,b) => {
let cellSort = a.x - b.x;

if(cellSort == 0) {
return a.node.val - b.node.val;
}

return cellSort;
});
result[idx] = result[idx].map((cell) => cell.node.val);
}

return result;
};

function createCell(node, x, y): {node: TreeNode, x:number, y:number} {
return {
"node": node,
"x": x, "y": y
};
}

I couldn't resist creating a data structure on top of the nodes for sorting 😉

You just read "Leet Code Solution 987 - Vertical Order Traversal of a Binary Tree". Please share if you liked it!
You can read more recent posts here.