Calculating key properties of a binary tree like its height and diameter.
The Height (or depth) of a binary tree is the number of edges on the longest path from the root node to a leaf node. The height of an empty tree is often defined as -1, and a tree with a single root node has a height of 0. The height can be calculated with a simple recursive function: `height(node) = 1 + max(height(node->left), height(node->right))`. The base case is a null node, which has a height of -1. This is a classic postorder traversal pattern. The Diameter (or width) of a binary tree is the number of nodes on the longest path between any two leaf nodes in the tree. This path may or may not pass through the root. Finding the diameter is more complex. For any given node, the longest path that passes through it is `1 + height(left subtree) + height(right subtree)`. Therefore, the diameter of the entire tree is the maximum of: (1) The diameter of the left subtree. (2) The diameter of the right subtree. (3) The longest path passing through the current root (`1 + height(left) + height(right)`). A naive recursive solution would calculate heights repeatedly, leading to an O(n^2) complexity. An optimized O(n) solution calculates the height and diameter in a single postorder traversal, returning both values from each recursive call.