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.
1#include <vector>
2#include <algorithm>
3using namespace std;
4class Node {
5public:
6 int val;
7 vector<Node*> children;
8
9 Node() {}
10
11 Node(int _val) {
12 val = _val;
13 }
14
15 Node(int _val, vector<Node*> _children) {
16 val = _val;
17 children = _children;
18 }
19};
20
21class Solution {
22public:
23 int maxDepth(Node* root) {
24 if (!root) return 0;
25 if (root->children.empty()) return 1;
26 int max_depth = 0;
27 for (auto child : root->children) {
28 max_depth = max(max_depth, maxDepth(child));
29 }
30 return 1 + max_depth;
31 }
32};
In the C++ implementation, a similar depth-first search approach is adopted. We use the standard library's max function to get the deepest path among children and return the value plus one to account for the current node level.
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
We use a deque to facilitate breadth-first traversal. In each loop iteration, we process all nodes at the current level and enqueue their children. Each iteration over the level represents moving a depth deeper, and we count these iterations to find the final maximum depth.