给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
题目地址:N叉树的最大深度
或直转到:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
- 我的题解
int myfunc(struct Node* root){
int max;
max=0;
if(root!=NULL){
if(root->numChildren!=0){
int* sz;
//万恶之源
sz=(int*)malloc(sizeof(int)*(root->numChildren));
//万恶之源
for (int i = 0; i < root->numChildren; i++) {
*(sz+i)=myfunc(*(root->children+i));
}
max=*sz;
for (int j = 1; j < root->numChildren; j++) {
if(max<*(sz+j)){
max=*(sz+j);
}
}
}
}//if
else{
max=-1;
}
return max+1;
}
int maxDepth(struct Node* root) {
return myfunc(root);
}
代码整体的逻辑结构和二叉树最大深度,也就是#104题的思路一样,不过需要灵活运用递归,理解递归的比二叉树思维要深一些的逻辑。
获得树的深度不需要按照遍历顺序,按照自己逻辑做题就可以。我利用动态创建数组方法构造numChildren大小的数组来装下每个数组的对应深度,二叉树就用左右子树递归,N叉树我利用for循环进行递归得到所有子结点的深度。最后通过选择法选出最大的。
如果结点是空就返回0,由于我返回的是max+1,空时max就置为-1了,和为0。
经过验证,我的思路是正确的,可是这涉及到一个优化问题。
如图:
原因也非常直观,由于我每次递归都创建了当前结点指向的numChildren数量个int空间,空间的创建是很消耗内存的,而递归中需要给每个结点都创建动态数组,因此可以继续进行优化,不利用动态创建数组而是传参的形式,或者花样使用递归。
- 我优化之后的成绩:
- 我优化之后的代码
int myfunc(struct Node* root){
int max;
max=0;
if(root!=NULL){
if(root->numChildren!=0){
//int* sz;
//
//sz=(int*)malloc(sizeof(int)*(root->numChildren));
//
max=myfunc(*(root->children));
for (int i = 0; i < root->numChildren-1; i++) {
if(max<myfunc(*(root->children+i+1))){
max=myfunc(*(root->children+i+1));
}
}
// max=*sz;
// for (int j = 1; j < root->numChildren; j++) {
// if(max<*(sz+j)){
// max=*(sz+j);
// }
// }
}
}//if
else{
max=-1;
}
return max+1;
}
int maxDepth(struct Node* root) {
return myfunc(root);
}
直接将max赋值为第一个孩子的深度,然后一个一个比较,省去了动态创建数组和选择法的内存,成绩明显提高了。!!!!!!!!!!