Last active
April 13, 2020 04:26
-
-
Save javi-aire/7968571117f3570e247dcdd339c199a2 to your computer and use it in GitHub Desktop.
Problem 11/30 of LeetCode 30-day challenge
This file contains hidden or 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
/** | |
* Definition for a binary tree node. | |
* function TreeNode(val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
*/ | |
/** | |
* @param {TreeNode} root | |
* @return {number} | |
*/ | |
var diameterOfBinaryTree = function(root) { | |
if(root === null){ | |
return 0; | |
} | |
// recursive helper func to help count | |
function hasChildren(node) { | |
if(node === null) { | |
return 0; | |
} | |
let leftChildren = hasChildren(node.left); | |
let rightChildren = hasChildren(node.right); | |
return leftChildren > rightChildren ? leftChildren + 1 : rightChildren + 1; | |
} | |
// should add from 2 recursive paths -- from the root, then from its children | |
let rootDiameter = hasChildren(root.left) + hasChildren(root.right); | |
let diameterOfChildren = Math.max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right)); | |
return rootDiameter > diameterOfChildren ? rootDiameter : diameterOfChildren; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment