Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 17, 2021 03:08
Show Gist options
  • Save CarlaTeo/996b25477b96fe7705793cba2ab95098 to your computer and use it in GitHub Desktop.
Save CarlaTeo/996b25477b96fe7705793cba2ab95098 to your computer and use it in GitHub Desktop.
[JS] Binary tree height
// Problem: https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem
function getHeight(head) {
if(!head) return -1;
const heights = new Set();
DFS(head, -1, heights);
return Math.max(...heights);
}
function DFS(node, height, heights) {
if(!node) {
heights.add(height);
return;
}
DFS(node.right, height + 1, heights);
DFS(node.left, height + 1, heights);
}
// ------------------------- Test ---------------------------//
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// head
// / \
// node1 node2
// / \
// node3 node4
// \
// node5
console.log(getHeight(null)); // -1
const head = new Node();
console.log(getHeight(head)); // 0
const node1 = new Node();
head.left = node1;
console.log(getHeight(head)); // 1
const node2 = new Node();
head.right = node2;
console.log(getHeight(head)); // 1
const node3 = new Node();
const node4 = new Node();
const node5 = new Node();
node2.left = node3;
node2.right = node4;
node3.right = node5;
console.log(getHeight(head)); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment