LeetCode 543: Diameter of Binary Tree

Problem Description

Explanation

To find the diameter of a binary tree, we need to calculate the maximum path length between any two nodes in the tree. This path may or may not pass through the root. We can solve this problem by recursively traversing the tree and calculating the height of each node. The diameter passing through a node is the sum of the heights of its left and right subtrees. We need to keep track of the maximum diameter found during the traversal.

  1. Recursively calculate the height of each node in the tree.
  2. For each node, calculate the diameter passing through that node as the sum of the heights of its left and right subtrees.
  3. Keep track of the maximum diameter found during the traversal.
  4. Return the maximum diameter as the result.

Time Complexity: O(n) where n is the number of nodes in the tree. Space Complexity: O(h) where h is the height of the tree.

Solutions

class Solution {
    int maxDiameter = 0;
    
    public int diameterOfBinaryTree(TreeNode root) {
        calculateHeight(root);
        return maxDiameter;
    }
    
    private int calculateHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }
        
        int leftHeight = calculateHeight(node.left);
        int rightHeight = calculateHeight(node.right);
        
        maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);
        
        return 1 + Math.max(leftHeight, rightHeight);
    }
}

Loading editor...