Skip to content

Instantly share code, notes, and snippets.

@adhrinae
Created June 11, 2018 15:47
Show Gist options
  • Save adhrinae/987545b3fdb5475a5c68c4f1a3d737ca to your computer and use it in GitHub Desktop.
Save adhrinae/987545b3fdb5475a5c68c4f1a3d737ca to your computer and use it in GitHub Desktop.
Getting Depth of Binary Tree
function Node(value = null, left = null, right = null) {
return {
value,
left,
right
}
}
const isEdgeLeaf = node => !node.left && !node.right
const getHeight = (node, height = 0) => {
if (isEdgeLeaf(node)) return height
const lval = node.left != null ? getHeight(node.left, height + 1) : -1
const rval = node.right != null ? getHeight(node.right, height + 1) : -1
return Math.max(lval, rval)
}
const tree = Node(
5,
Node(
3,
Node(8, null, null),
Node(7,
Node(1, null, null),
null)),
Node(
4,
null,
Node(6, null, null))
)
const height = getHeight(tree)
console.log(height) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment