Skip to content

Instantly share code, notes, and snippets.

@javi-aire
Last active April 13, 2020 04:26
Show Gist options
  • Save javi-aire/7968571117f3570e247dcdd339c199a2 to your computer and use it in GitHub Desktop.
Save javi-aire/7968571117f3570e247dcdd339c199a2 to your computer and use it in GitHub Desktop.
Problem 11/30 of LeetCode 30-day challenge
/**
* 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