Created
September 6, 2021 22:42
-
-
Save misterpoloy/946020a1325beea39e1227750f875172 to your computer and use it in GitHub Desktop.
Get diameter of a binary tree with javascript recursive impelemntation
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 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; | |
} |
Author
misterpoloy
commented
Sep 6, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment