求二叉树的宽度

zhangyue_lala 2017-11-28 04:16:27
int deepth = 0; //遍历的层
int width[MAXDEEP] = {0}; //存放各层宽度的数组

void TreeWidth(Tree t){
if (t == NULL) {
return;
}
if (deepth == 0) {
width[0] = 1;
}
if (t->left != NULL) {
width[deepth+1] += 1;
deepth += 1;
TreeWidth(t->left);
}
if (t->right != NULL) {
width[deepth+1] += 1;
deepth+=1;
TreeWidth(t->right);
}
deepth-=1;
}

倒数第二行,为什么deepth 要-1???
很迷
...全文
583 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ooolinux 2017-11-29
  • 打赏
  • 举报
回复
int depth = 0; //遍历的层
int width[MAXDEPTH] = {0}; //存放各层宽度的数组

void TreeWidth(Tree t){
    if (t == NULL) {
        return;
    }
    if (depth == 0) {
        width[0] = 1;
    }
    if (t->left != NULL) {
        width[++depth] ++;
        printf("往左子树,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]);
        TreeWidth(t->left);
    }
    if (t->right != NULL) {
        width[++depth] ++;
        printf("往右子树,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]);
        TreeWidth(t->right);
    }
    depth--;
    printf("返回上一层,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]);
}
ooolinux 2017-11-29
  • 打赏
  • 举报
回复
我明白了,因为要计算各层的宽度,从TreeWidth(t->left); 或TreeWidth(t->right);递归调用中逐层return的时候,要返回到上一层,需要 depth-=1; 代码中可以增加一下printf语句,会比较清楚: void TreeWidth(Tree t){ if (t == NULL) { return; } if (depth == 0) { width[0] = 1; } if (t->left != NULL) { width[depth+1] += 1; depth += 1; printf("往左子树,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]); TreeWidth(t->left); } if (t->right != NULL) { width[depth+1] += 1; depth+=1; printf("往右子树,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]); TreeWidth(t->right); } depth-=1; printf("返回上一层,当前在第%d层,当前计算的宽度为%d\n",depth,width[depth]); }
ooolinux 2017-11-28
  • 打赏
  • 举报
回复
int depth = 0; //遍历的层 作为一个全局变量, depth-=1; 是不是为了TreeWidth 以后回到原来的depth,不过如果二叉树只有一个根节点,调用TreeWidth 以后depth等于-1了,似乎有bug。 注释掉 depth-=1; 这一行看看有什么不同? 还有,你这个代码来自哪里?

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧