Sponsored
Sponsored
This approach leverages the recursive nature of trees to calculate the depth. For each node, if it has no children, it is a leaf and has depth 1. Otherwise, recursively calculate the depth of each child and take the maximum depth found among all children, adding 1 for the current node to account for the path to parent.
The time complexity is O(n), where n is the number of nodes in the tree. Each node is visited once. The space complexity is O(h) where h is the height of the tree, representing the function call stack during the recursion.
1using System;
2using System.Collections.Generic;
3
4public class Node {
5 public int val;
6 public IList<Node> children;
7 public Node() {}
8 public Node(int _val) {
9 val = _val;
10 children = new List<Node>();
11 }
12 public Node(int _val, IList<Node> _children) {
13 val = _val;
14 children = _children;
15 }
16}
17
18public class Solution {
19 public int MaxDepth(Node root) {
20 if (root == null) return 0;
21 if (root.children.Count == 0) return 1;
22 int maxDepth = 0;
23 foreach (var child in root.children) {
24 maxDepth = Math.Max(maxDepth, MaxDepth(child));
25 }
26 return maxDepth + 1;
27 }
28}
In C#, the recursive function MaxDepth is employed similar to other language implementations. We iterate over each child node, compute their depths, and keep track of the maximum depth found.
This approach utilizes BFS using a queue to iteratively compute tree depth. Nodes are enqueued level by level. At each level, we count its nodes, dequeuing them and enqueueing their children, indicating traversing to the next tree level. We increment a level counter as we progress deeper into the tree.
The time complexity is O(n) as we process each node once. The space complexity is O(n) for holding nodes of the widest level in the queue.
1
In this Java solution, BFS is applied iteratively. Nodes of each level are processed by polling the queue, and their children are enqueued. We increment the depth counter at each completed level to determine the tree's depth.