This approach involves using a recursive function that traverses the tree in a depth-first manner. For each node, calculate the maximum depth of its left and right subtrees, and add 1 for the current node itself. The function returns the maximum of these two values. This provides an elegant and intuitive solution, leveraging the inherent recursive structure of trees.
Time Complexity: O(n) where n is the number of nodes, as each node is visited once.
Space Complexity: O(h) where h is the height of the tree, due to the stack space in recursion.
1function TreeNode(val, left, right) {
2 this.val = (val===undefined ? 0 : val)
3 this.left = (left===undefined ? null : left)
4 this.right = (right===undefined ? null : right)
5}
6
7var maxDepth = function(root) {
8 if (!root) return 0;
9 return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
10};
In JavaScript, similar strategies apply, using recursive function calls to determine the maximum depth by comparing subtree depths. If the node is null, return 0.
This approach involves using a queue to perform a Breadth-First Search (BFS) on the tree. By iterating level by level, we increment the depth counter with each level traversed completely.
Time Complexity: O(n) due to each node being visited once.
Space Complexity: O(n) where n is the maximum number of nodes at any level.
1#include <queue>
2using namespace std;
3struct TreeNode {
4 int val;
5 TreeNode *left;
6 TreeNode *right;
7 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8};
9
10int maxDepth(TreeNode* root) {
11 if (!root) return 0;
12 queue<TreeNode*> q;
13 q.push(root);
14 int depth = 0;
15 while (!q.empty()) {
16 int level_size = q.size();
17 for (int i = 0; i < level_size; ++i) {
18 TreeNode* node = q.front(); q.pop();
19 if (node->left) q.push(node->left);
20 if (node->right) q.push(node->right);
21 }
22 depth++;
23 }
24 return depth;
25}
Using a queue
from the Standard Template Library (STL), nodes of each level are processed iteratively. Each loop iteration processes a full level, incrementing the depth with each completed level.