KatInterview

543. Diameter of Binary Tree

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the diameter of a binary tree, which is defined as the length of the longest path between any two nodes. The path's length is the number of edges. A crucial point is that this longest path may or may not pass through the root of the tree.

Solution

Diameter of Binary Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        self.max_diameter = 0

        def height(node):
            """
            This helper function serves two purposes:
            1. It returns the height of the subtree rooted at 'node'.
               Height is defined as the number of nodes on the longest path from the node down to a leaf.
            2. It updates the overall maximum diameter found so far as a side effect.
            """
            # Base case: an empty tree has a height of 0.
            if not node:
                return 0
            
            # Recursively find the height of left and right subtrees.
            left_height = height(node.left)
            right_height = height(node.right)

            # The diameter of a path passing through the current node is the sum of the heights
            # of its left and right subtrees. We update the max_diameter if this path is longer.
            self.max_diameter = max(self.max_diameter, left_height + right_height)

            # The height of the tree rooted at the current node is 1 (for the current node) plus
            # the maximum height of its left and right subtrees.
            return 1 + max(left_height, right_height)

        height(root)
        return self.max_diameter

Diameter of Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int maxDiameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        height(root);
        return maxDiameter;
    }

    /**
     * This helper function serves two purposes:
     * 1. It returns the height of the subtree rooted at 'node'.
     *    Height is defined as the number of nodes on the longest path from the node down to a leaf.
     * 2. It updates the overall maximum diameter found so far as a side effect.
     */
    private int height(TreeNode node) {
        // Base case: an empty tree has a height of 0.
        if (node == null) {
            return 0;
        }

        // Recursively find the height of left and right subtrees.
        int leftHeight = height(node.left);
        int rightHeight = height(node.right);

        // The diameter of a path passing through the current node is the sum of the heights
        // of its left and right subtrees. We update the maxDiameter if this path is longer.
        maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);

        // The height of the tree rooted at the current node is 1 (for the current node) plus
        // the maximum height of its left and right subtrees.
        return 1 + Math.max(leftHeight, rightHeight);
    }
}

Diameter of Binary Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        maxDiameter = 0;
        height(root);
        return maxDiameter;
    }

private:
    int maxDiameter;

    /**
     * This helper function serves two purposes:
     * 1. It returns the height of the subtree rooted at 'node'.
     *    Height is defined as the number of nodes on the longest path from the node down to a leaf.
     * 2. It updates the overall maximum diameter found so far as a side effect.
     */
    int height(TreeNode* node) {
        // Base case: an empty tree has a height of 0.
        if (!node) {
            return 0;
        }

        // Recursively find the height of left and right subtrees.
        int leftHeight = height(node->left);
        int rightHeight = height(node->right);

        // The diameter of a path passing through the current node is the sum of the heights
        // of its left and right subtrees. We update the maxDiameter if this path is longer.
        maxDiameter = std::max(maxDiameter, leftHeight + rightHeight);

        // The height of the tree rooted at the current node is 1 (for the current node) plus
        // the maximum height of its left and right subtrees.
        return 1 + std::max(leftHeight, rightHeight);
    }
};

Diameter of Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function diameterOfBinaryTree(root: TreeNode | null): number {
    let maxDiameter = 0;

    /**
     * This helper function serves two purposes:
     * 1. It returns the height of the subtree rooted at 'node'.
     *    Height is defined as the number of nodes on the longest path from the node down to a leaf.
     * 2. It updates the overall maximum diameter found so far as a side effect.
     */
    function height(node: TreeNode | null): number {
        // Base case: an empty tree has a height of 0.
        if (!node) {
            return 0;
        }

        // Recursively find the height of left and right subtrees.
        const leftHeight = height(node.left);
        const rightHeight = height(node.right);

        // The diameter of a path passing through the current node is the sum of the heights
        // of its left and right subtrees. We update the maxDiameter if this path is longer.
        maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);

        // The height of the tree rooted at the current node is 1 (for the current node) plus
        // the maximum height of its left and right subtrees.
        return 1 + Math.max(leftHeight, rightHeight);
    }

    height(root);
    return maxDiameter;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.