543. Diameter of Binary Tree

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var diameterOfBinaryTree = function(root) {
    let result = 0;
    
    const dfs = (rt) => {
        if (!rt) {
            // The height of a null node is -1
            // The height of a leaf node is 0
            return -1;
        }
        
        const left = dfs(rt.left);
        const right = dfs(rt.right);
        const diameter = 2 + left + right;
        result = Math.max(result, diameter);
        const height = 1 + Math.max(left, right);
        
        return height;
    }
    
    dfs(root);
    
    return result;
};

Complexity

  • Time Complexity: O(N), where N is the number of nodes.
  • Space Complexity: O(N), where N is the size of the implicit call stack.

All Solutions