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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int x) { val = x; }
6}
7
8public class Solution {
9 public int MaxDepth(TreeNode root) {
10 if (root == null) return 0;
11 return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right));
12 }
13}
C# uses a similar pattern to other languages: check for null, invoke recursion, and apply the Math.Max
function across child nodes to determine depth.
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;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12 public int MaxDepth(TreeNode root) {
13 if (root == null) return 0;
14 Queue<TreeNode> q = new Queue<TreeNode>();
15 q.Enqueue(root);
16 int depth = 0;
17 while (q.Count > 0) {
18 int levelSize = q.Count;
19 for (int i = 0; i < levelSize; i++) {
20 TreeNode node = q.Dequeue();
21 if (node.left != null) q.Enqueue(node.left);
22 if (node.right != null) q.Enqueue(node.right);
23 }
24 depth++;
25 }
26 return depth;
27 }
28}
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.