Given the root of a binary tree, find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.
The idea is to recursively compute the height of the left and right subtrees for each node. The height of the current node is then calculated by 1 + max(leftHeight, rightHeight). The recursion bottoms out when we reach to a null node, which contributes a height of 0.
Consider the following tree for example to understand the flow.
Time Complexity: O(n) Auxiliary Space: O(h) where h is height of the binary tree. The height can be at most equal to number of nodes in case of skewed tree and O(Log n) in case of a balanced tree
Level Order Traversal
In level order traversal (BFS), we process the tree level by level. At each step, we note the number of nodes in the current level, process exactly those nodes, and enqueue their children. After finishing each level, we increment the depth counter. By the time the queue is empty, the counter reflects the maximum depth or height of the tree.
Output
2
Time Complexity: O(n) Auxiliary Space: O(n) where n is number of nodes. A more precise value of of space would be O(w) where w is width of the binary tree.