</>

20. Diameter of Binary Tree

Easy NeetCode 150
Trees Time O(N) Space O(H)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Trees
Time
O(N)
Space
O(H)

Standard Solution (C++)

SummaryGiven the root of a binary tree, find the length of the longest path between any two nodes, measured in number of edges. The path does not need to pass through the root.

Approach
  • Perform a single post-order DFS so that each node receives the height of its left and right subtrees before computing its own contribution.
  • At each node, the diameter candidate passing through that node equals leftHeight + rightHeight (edges going down both sides).
  • Track the global maximum diameter in an integer reference as the recursion unwinds, and return height (max(left, right) + 1) up the call stack.
  • This one-pass traversal avoids redundant recomputation that would occur if height and diameter were computed separately.
#include <algorithm>
using namespace std;

// 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 {
    // Returns the height of the subtree rooted at node (number of edges to deepest leaf).
    // Updates `best` with the longest diameter seen so far.
    int height(TreeNode* node, int& best) {
        if (!node) return 0;

        int leftH  = height(node->left,  best);
        int rightH = height(node->right, best);

        // Diameter through this node = edges going left + edges going right.
        best = max(best, leftH + rightH);

        return max(leftH, rightH) + 1;
    }

public:
    int diameterOfBinaryTree(TreeNode* root) {
        int best = 0;
        height(root, best);
        return best;
    }
};
Time O(n) Space O(h), where h is the tree height — O(log n) for a balanced tree, O(n) worst case for a skewed tree

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (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:
    std::pair<int, int> dfs(TreeNode* root) { // return the depth and the diameter of the tree
        if(!root)
            return {0, 0};
        
        auto [leftDepth, leftDiameter] = dfs(root->left);
        auto [rightDepth, rightDiameter] = dfs(root->right);

        int diameterThroughRoot=leftDepth+rightDepth;
        
        int currentDiameter=std::max({leftDiameter, rightDiameter, diameterThroughRoot});
        int currentDepth=std::max(leftDepth, rightDepth)+1;
        
        return {currentDepth, currentDiameter};
    }
    int diameterOfBinaryTree(TreeNode* root) {
        return dfs(root).second;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space). 
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N).
Time O(N) Space O(H)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern