Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created September 6, 2021 22:42
Show Gist options
  • Save misterpoloy/946020a1325beea39e1227750f875172 to your computer and use it in GitHub Desktop.
Save misterpoloy/946020a1325beea39e1227750f875172 to your computer and use it in GitHub Desktop.
Get diameter of a binary tree with javascript recursive impelemntation
function getDiameterAndHeight(tree) {
if (tree === null) return { diameter: 0, height: 0 }
const leftTreeInfo = getDiameterAndHeight(tree.left)
const rightTreeInfo = getDiameterAndHeight(tree.right)
const diameterFromRoot = leftTreeInfo.height + rightTreeInfo.height
const longestDiameterSoFar = Math.max(leftTreeInfo.diameter, rightTreeInfo.diameter)
const diameter = Math.max(diameterFromRoot, longestDiameterSoFar)
const height = Math.max(leftTreeInfo.height, rightTreeInfo.height) + 1
return { diameter, height }
}
function binaryTreeDiameter(tree) {
// Write your code here.
return getDiameterAndHeight(tree).diameter;
}
@misterpoloy
Copy link
Author

screenshot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment