Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 9, 2020 07:56
Show Gist options
  • Save RP-3/0d83e1f7ca79969455e9fa2b20245b81 to your computer and use it in GitHub Desktop.
Save RP-3/0d83e1f7ca79969455e9fa2b20245b81 to your computer and use it in GitHub Desktop.
/*
Idea: We need to find a way to know the
horizontal position of a given node. Then
we can track the max and min horizontal
position at each depth, and subtract them
to get the max horizontal distance between
two nodes.
Note: Since leetcode says the width between
just one node and itself is 1 (not zero) we
have to add 1 to the end result.
*/
var widthOfBinaryTree = function(root) {
if(!root) return 0;
const mins = [];
const maxs = [];
let result = 0;
const traverse = (node, pos, depth) => {
if(!node) return;
if(mins[depth] === undefined) mins[depth] = pos;
if(maxs[depth] === undefined) maxs[depth] = pos;
mins[depth] = Math.min(mins[depth], pos);
maxs[depth] = Math.max(maxs[depth], pos);
result = Math.max(result, maxs[depth] - mins[depth]);
traverse(node.left, pos*2, depth+1);
traverse(node.right, pos*2+1, depth+1);
};
traverse(root, 0, 0);
return result === NaN ? 1 : result; // Bullshit test case.
// Since the position of each node doubles at each level,
// after 32 levels we could have an integer overflow.
// AFAIK there's no tidy way to work around this...
// This 1 is just coding to the test cases.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment