Algo-Sim › Binary Trees & BST

Diameter of Binary Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

The longest path bends at some node: track left height + right height at every node while returning heights.

Problem

The diameter of a binary tree is the number of edges on the longest path between any two nodes; the path does not have to pass through the root. Return the diameter.

Constraints

Edge cases to test

Follow-up questions

Edges or nodes?
This counts edges, so the answer is left height + right height at the best node. Check which one the interviewer means.
What about a general tree or graph?
For a tree: BFS to the farthest node, then BFS again; the second distance is the diameter: O(n).

Solution

Java

private int best = 0;

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

private int height(TreeNode node) {
    if (node == null) return 0;
    int left = height(node.left);
    int right = height(node.right);
    best = Math.max(best, left + right);
    return 1 + Math.max(left, right);
}

Python

def diameter_of_binary_tree(root):
    best = 0

    def height(node):
        nonlocal best
        if not node:
            return 0
        left = height(node.left)
        right = height(node.right)
        best = max(best, left + right)
        return 1 + max(left, right)

    height(root)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int best = 0;

    int diameterOfBinaryTree(TreeNode *root) {
        height(root);
        return best;
    }

    int height(TreeNode *node) {
        if (node == nullptr)
            return 0;
        int left = height(node->left);
        int right = height(node->right);
        best = std::max(best, left + right);
        return 1 + std::max(left, right);
    }
};

More Binary Trees & BST problems