学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

二叉树的问题

二叉树的问题

/* Note:Your choice is C IDE */
#include "stdio.h"
#include<stdlib.h>
typedef struct bitnode
{
    int data;
    struct bitnode *lchild,*rchild;
}bitnode,*bittree;
bittree cre_tree()
{
    int x;
    bittree root;
    scanf("%d",&x);
    if(x==-1)root=NULL;
    else
    {
        root=(bittree)malloc(sizeof(bitnode));
        root->data=x;
        root->lchild=cre_tree();
        root->rchild=cre_tree();
    }
    return root;
}
void preorder(bittree root)   
{
    if(root)
    {
        printf("%4d",root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}
void inorder(bittree root)
{
    if(root)
    {
        inorder(root->lchild);
        printf("%4d",root->data);
        inorder(root->rchild);
    }
}
void postorder(bittree root)
{
    if(root)
    {
        postorder(root->lchild);
        postorder(root->rchild);
        printf("%4d",root->data);
    }
}
void main()
{
    bittree root;
    root=(bittree)malloc(sizeof(bitnode));
    root=cre_tree();
    preorder(root);printf("\n\n");
    inorder(root);printf("\n\n");
    postorder(root);printf("\n\n");
}
大家帮我看看,是那里出了问题,为什么运行的结果没有全对。

TOP

还好啊..要明白建树顺序
比如你输入 4 4 要知道输入几个-1才结束
    4
  4    -1
-1 -1
一旦你忘记了..数据就是错的了
学习需要安静。。海盗要重新来过。。

TOP

回复 1# 的帖子

那你 能和我说说建树的顺序吗?为什么后序和中序的输出都一样啊 !
抽刀断水水更流,举杯消愁愁更愁。

TOP

我试过是不一样的
先是左子树..当你-1时当前左子树结束..建立当前左子树的兄弟子树..要明确是怎么样结束就可以了  1 2 -1 -1 3 -1 -1 你看看呢
学习需要安静。。海盗要重新来过。。

TOP

谢谢了。果然不一样,看来输入我还是不大了解。
抽刀断水水更流,举杯消愁愁更愁。

TOP

发新话题