Skip to content

Instantly share code, notes, and snippets.

@wataruoguchi
Created July 27, 2019 05:03
Show Gist options
  • Save wataruoguchi/28869c8bf9b2b007926082b05e007d25 to your computer and use it in GitHub Desktop.
Save wataruoguchi/28869c8bf9b2b007926082b05e007d25 to your computer and use it in GitHub Desktop.
Print a Binary Tree in Vertical Order | Set 1
// https://www.geeksforgeeks.org/print-binary-tree-vertical-order/
class Node {
constructor(val, left, right) {
this.val = val;
this.left = left;
this.right = right;
}
}
function verticalOrder(root, arr) {
let min = 0;
let max = 0;
function findMinMax(root, hd) {
if (!root) {
return;
}
if (hd < min) {
min = hd;
} else if (hd > max) {
max = hd;
}
findMinMax(root.left, hd - 1);
findMinMax(root.right, hd + 1);
}
function printVerticalLine(node, lineNo, hd) {
if (!node) return;
if (hd === lineNo) arr.push(node.val);
printVerticalLine(node.left, lineNo, hd - 1);
printVerticalLine(node.right, lineNo, hd + 1);
}
function getRange(min, max) {
const range = max - min;
let idx;
let arr = [];
for (idx = 0;idx < range; idx++) {
arr.push(min + idx);
}
return arr;
}
findMinMax(root, 0);
const range = getRange(min, max + 1);
for (const lineNo in range) {
printVerticalLine(root, range[lineNo], 0);
}
return arr;
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
root.right.right.right = new Node(9);
console.log(verticalOrder(root, []).join(',') === '4,2,1,5,6,3,8,7,9');
// https://practice.geeksforgeeks.org/problems/print-a-binary-tree-in-vertical-order/1
const rootEx1 = new Node(1);
rootEx1.left = new Node(2);
rootEx1.right = new Node(3);
rootEx1.right.left = new Node(5);
console.log(verticalOrder(rootEx1, []).join(',') === '2,1,5,3');
const rootEx2 = new Node(1);
rootEx2.right = new Node(2);
rootEx2.left = new Node(3);
console.log(verticalOrder(rootEx2, []).join(',') === '3,1,2');
const rootEx3 = new Node(10);
rootEx3.left = new Node(20);
rootEx3.right = new Node(30);
rootEx3.left.left = new Node(40);
rootEx3.left.right = new Node(60);
console.log(verticalOrder(rootEx3, []).join(',') === '40,20,10,60,30');
const rootEx4 = new Node(1);
rootEx4.left = new Node(2);
rootEx4.right = new Node(3);
rootEx4.left.right = new Node(4);
rootEx4.left.right.right = new Node(5);
console.log(verticalOrder(rootEx4, []).join(',') === '2,1,4,3,5'); // For some reason it fails
console.log(verticalOrder(rootEx4, []).join(',') === '2,1,4,5,3'); // It's ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment