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 <stdio.h>
2#include <stdlib.h>
3
4struct Node {
5 int val;
6 int numChildren;
7 struct Node** children;
8};
9
10int maxDepth(struct Node* root) {
11 if (!root) return 0;
12 if (root->numChildren == 0) return 1;
13 int maxDepthVal = 0;
14 for (int i = 0; i < root->numChildren; i++) {
15 int depth = maxDepth(root->children[i]);
16 if (depth > maxDepthVal) {
17 maxDepthVal = depth;
18 }
19 }
20 return maxDepthVal + 1;
21}
In C, we perform DFS recursively by iterating over each node's children to find the maximum depth. Given C's nature, we manage memory and pointers directly, yet the algorithmic concept remains similar – recursing through each child node.
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
Implementation of BFS using a custom queue in C. At each level, nodes are dequeued, and their children are enqueued. The depth counter increments at each level completion, indicating progress in traversal depth.