Algorithm: Diameter of Binary Tree

/**
 * Definition for a binary tree node.
**/
class TreeNode
{
    constructor(value, left, right)
    {
        this.value = value
        this.left = left
        this.right = right
    }
}


/**
 * @param {TreeNode} root
 * @return {number}
 */
let diameterOfBinaryTree = (root) =>
{
    if (!root) return 0

    let lheight = calculateHeight(root.left)
    let rheight = calculateHeight(root.right)

    let ldiameter = diameterOfBinaryTree(root.left)
    let rdiameter = diameterOfBinaryTree(root.right)

    return Math.max(lheight + rheight, Math.max(ldiameter, rdiameter))
};

let calculateHeight = (node) =>
{
    if (!node) return 0

    return 1 + Math.max(calculateHeight(node.left), calculateHeight(node.right))
}

Leave a Reply

Your email address will not be published. Required fields are marked *