Sponsored
Sponsored
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.
1#include <algorithm>
2struct TreeNode {
3 int val;
4 TreeNode *left;
5 TreeNode *right;
6 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
7};
8
9int maxDepth(TreeNode* root) {
10 if (!root) return 0;
11 return 1 + std::max(maxDepth(root->left), maxDepth(root->right));
12}This C++ solution also uses recursion. The std::max function is used to determine the larger depth between the left and right subtrees. The recursive nature mirrors the tree's structure.
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.
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public int MaxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
int depth = 0;
while (q.Count > 0) {
int levelSize = q.Count;
for (int i = 0; i < levelSize; i++) {
TreeNode node = q.Dequeue();
if (node.left != null) q.Enqueue(node.left);
if (node.right != null) q.Enqueue(node.right);
}
depth++;
}
return depth;
}
}C# uses a Queue to allow level-wise tree traversal. Each level's nodes insert their children into this queue, with depth adjusted after processing one full level.