题目:
算法思想: 一种是递归,相当于深度优先搜索求树的高度,写起来比较简单。另一种是层次遍历,用队列维护,队列的元素可以使用pair<node,int>,方便记录当前层数。这里只给出递归写法。
代码:
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL)
return 0;
int maxdepth = 0;
for(int i = 0;i < root->children.size();i++)
{
maxdepth = max(maxdepth,maxDepth(root->children[i]));
}
return maxdepth+1;
}
};