Created
June 11, 2018 15:47
-
-
Save adhrinae/987545b3fdb5475a5c68c4f1a3d737ca to your computer and use it in GitHub Desktop.
Getting Depth of Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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