1. Top-Down Height Calculation
Intuition
Define height(node). At each node, compute height(node.left) + height(node.right), and take the maximum across all nodes by recursing.
When to apply: Basic baseline check.
Algorithm
- Step 1: Define height(node) returning 1 + max(height(left), height(right)).
- Step 2: For each node, local diameter = height(left) + height(right).
- Step 3: Return max(local, diameter(left), diameter(right)).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int height(TreeNode* node) { if (!node) return 0; return 1 + max(height(node->left), height(node->right)); } int diameterOfBinaryTree(TreeNode* root) { if (!root) return 0; int cur = height(root->left) + height(root->right); int l = diameterOfBinaryTree(root->left); int r = diameterOfBinaryTree(root->right); return max({cur, l, r}); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— Repeatedly computes heights for subtrees at every level, taking O(n2) worst case on skewed trees. - Space complexity:
O(h)— Call stack takes O(h) space.