一般看到树 ,就喜欢递归。 参考二叉树的最大深度。
int maxDepth(Node* root) //递归写法
{
if (root == NULL)
return 0;
else
{
int Max = 0;
for (auto i = 0; i < root->children.size(); i++)
Max = max(Max, maxDepth(root->children[i]));
return Max + 1;
}
}
非递归写法,层次遍历
int maxDepth(Node* root)//非递归写法
{
if (root == NULL)
return 0;
else
{
int dep = 0;
queue< Node*> temp;
temp.push(root);
while (!temp.empty())
{
dep++;
int n = temp.size();
for (int i = 0; i < n; i++)
{
Node *p = temp.front();
for (auto j = 0; j < p->children.size(); j++)
{
temp.push(p->children[j]);
}
temp.pop();
}
}
return dep;
}
}