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.
1import java.util.List;
2class Node {
3 public int val;
4 public List<Node> children;
5 public Node() {}
6 public Node(int _val) {
7 val = _val;
8 }
9 public Node(int _val, List<Node> _children) {
10 val = _val;
11 children = _children;
12 }
13}
14
15class Solution {
16 public int maxDepth(Node root) {
17 if (root == null) return 0;
18 if (root.children.isEmpty()) return 1;
19 int maxDepth = 0;
20 for (Node child : root.children) {
21 maxDepth = Math.max(maxDepth, maxDepth(child));
22 }
23 return 1 + maxDepth;
24 }
25}
Using Java, we employ a similar recursive strategy. For each node, we recursively find the maximum depth among children and add 1 for the current node. This is a direct translation of DFS for tree depth calculation.
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.