Problem
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary
tree:
We should return its max depth, which is 3.
Note:
- The depth of the tree is at most
1000
. - The total number of nodes is at most
5000
.
Solution: Recursion
Time complexity: O(n)
Space complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua // Running time: 40 ms class Solution { public: int maxDepth(Node* root) { if (root == nullptr) return 0; int depth = 0; for (auto child : root->children) depth = max(depth, maxDepth(child)); return depth + 1; } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment