c - 二叉树的层序遍历中出现运行时错误

标签 c binary-tree

出现运行时错误,找不到我错在哪里

我认为存在一些与内存相关的问题,但无法追踪

#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node* leftchild;
    struct node* rightchild;
};

用于创建新节点

struct node* newnode(int data)
{
    struct node* node=malloc(sizeof(struct node));
    node->data=data;
    node->leftchild=NULL;
    node->rightchild=NULL;
    return node;
 }

树的高度

int height(struct node* root)
{
    int lheight,rheight;
    if(root==NULL)
        return 0;
    else
    {
        lheight=height(root->leftchild);
        rheight=height(root->rightchild);
    }
    if(lheight>rheight)
        return lheight+1;
    else 
        return rheight+1;
}

打印节点的递归函数

void printlevelorder(struct node* root,int current,int level)
{
    if(current==level)
    {
        printf("%d ",root->data);
        return;
    }
    else
    {
        printlevelorder(root->leftchild,current+1,level);
        printlevelorder(root->rightchild,current+1,level);
    }

 }

遍历各个级别的函数

void levelorder(struct node* root)
{
    int h,i;
    h= height(root);
    if(h!=0){
        for(i=1;i<=h;i++)
        {
            printlevelorder(root,1,i);
        }
    }
    else 
        printf("Tree not exist\n");
}

用于测试功能的驱动程序

int main()
{
    struct node* root=newnode(1);
    root->leftchild=newnode(2);
    root->rightchild=newnode(7);
    root->leftchild->leftchild=newnode(3);
    root->leftchild->rightchild=newnode(6);
    root->leftchild->leftchild->leftchild=newnode(4);
    root->leftchild->leftchild->leftchild->rightchild=newnode(5);
    root->rightchild->leftchild=newnode(9);
    root->rightchild->rightchild=newnode(8);
    levelorder(root);
    return 0;
}

最佳答案

current 是树的最大高度(在您的情况下为 5)时,您将停止递归调用 printlevelorder 函数。由于root的右子树的高度小于5,当current足够大时,当你遍历该子树时,你会遇到段错误。更好的解决方案是在遇到 NULL 节点时停止递归调用,而不是检查 current 何时达到 5。

关于c - 二叉树的层序遍历中出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953060/

相关文章:

ruby - 编写一个比较两棵树的函数,如果它们在结构和值上相等则返回 true,否则返回 false

java - 没有setter的Java中的平衡二叉树

c - execvp() 不让我

c - 为什么 Visual Studio 2015 找不到 libxml2 的文件依赖项 iconv.h?

c++ - 如何初始化 TCHAR 数组?

c - Eclipse IDE 中代码的工作顺序

c - 将字符串传递给 scanf

C - 从二叉树中删除节点

c++ - 模板化类 const 限定符构造函数

c - 找到一条到达叶子的路径等于sum(不是BST)