题目:

算法思想: 一种是递归,相当于深度优先搜索求树的高度,写起来比较简单。另一种是层次遍历,用队列维护,队列的元素可以使用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;
}
};
博客介绍了求树高度的两种算法思想,一是递归,相当于深度优先搜索,写法简单;二是层次遍历,用队列维护。文中仅给出了递归写法的代码。
3495

被折叠的 条评论
为什么被折叠?



