yuhuajinghong
惊鸿之羽
2020-02-13 19:31

【c语言数据结构】遍历二叉树

  • c语言

代码一运行就停止工作,求助大神,看看我的问题是什么

#include<stdio.h>
#include<stdlib.h>
typedef struct treeNode//定义
{
    int data;
    struct treeNode *left;
    struct treeNode *right;
}treenode,*TreeNode;
void pre(TreeNode node)//前序遍历
{

    if(node==NULL)
        return ;
    printf("%d ", node->data);
    pre(node->left);
    pre(node->right);
}
void mid(TreeNode node)//中序遍历
{

    if(node==NULL)
        return ;
    mid(node->left);
    printf("%d ", node->data);
    mid(node->right);
}
void beh(TreeNode node)//后序遍历
{

    if(node==NULL)
        return ;
    beh(node->left);
    beh(node->right);
    printf("%d ", node->data);
}
void tree(TreeNode one)//定义一个现成的二叉树
{
    one=(TreeNode*)malloc(sizeof(treenode));
    one->left=(TreeNode*)malloc(sizeof(treenode));
    one->right=(TreeNode*)malloc(sizeof(treenode));
    one->right->left=(TreeNode*)malloc(sizeof(treenode));
    one->right->right=(TreeNode*)malloc(sizeof(treenode));
    one->left->left=(TreeNode*)malloc(sizeof(treenode));
    one->left->right=(TreeNode*)malloc(sizeof(treenode));
    one->right->left->left=(TreeNode*)malloc(sizeof(treenode));
    one->right->left->right=(TreeNode*)malloc(sizeof(treenode));
    one->right->right->left=(TreeNode*)malloc(sizeof(treenode));
    one->right->right->right=(TreeNode*)malloc(sizeof(treenode));

    one->data=3;
    one->left->data=9;
    one->right->data=20;
    one->right->left->data=15;
    one->right->right->data=7;
}
void main()//主方法
{
    TreeNode  one;
    tree(one);
    printf("该二叉树的前序遍历为:\n");
    pre(one);
    printf("该二叉树的中序遍历为:\n");
    mid(one);
    printf("该二叉树的后序遍历为:\n");
    beh(one);
}


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答