1,题目要求
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.
计算一颗多叉树的最大深度。
2,题目思路
求一颗树的最大深度,对于二叉树来说比较简单:
int maxDepth(TreeNode* node)
{
if(node == nullptr)
return 0;
return max(maxDepth(node->left), maxDepth(node->right))+1;
}
当拓展到多叉树时,因为节点是保存在vector中,因此,此时原理和二叉树是相似,只不过不再是仅仅对左右子树进行判断,而是对vector中所有节点都进行判断。
3,程序源码
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
int maxDepth(Node* root) {
if(root == nullptr) return 0;
int dep = 0;
for(auto n : root->children)
dep = max(dep, maxDepth(n));
return dep + 1;
}
};