给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 深度优先遍历,逐个节点返回深度,得出最大深度
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
//思路:深度优先遍历
//N 叉树的最大深度
int maxDepth(struct Node* root) {
if (root == NULL) {
return 0;
}
int max = 0;
for (int i = 0; i < root->numChildren; i++) {
//递归孩子的深度,找到最大深度
const int depth = maxDepth(root->children[i]);
if (max < depth) {
max = depth;
}
}
//孩子的最大深度加上自身
return max + 1;
}