当前位置: 代码迷 >> C语言 >> 二叉树的问题
  详细解决方案

二叉树的问题

热度:299   发布时间:2008-05-08 22:00:38.0
二叉树的问题
/* 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");
}
大家帮我看看,是那里出了问题,为什么运行的结果没有全对。
搜索更多相关的解决方案: 二叉树  

----------------解决方案--------------------------------------------------------
还好啊..要明白建树顺序
比如你输入 4 4 要知道输入几个-1才结束
    4
  4    -1
-1 -1
一旦你忘记了..数据就是错的了
----------------解决方案--------------------------------------------------------
回复 1# 的帖子
那你 能和我说说建树的顺序吗?为什么后序和中序的输出都一样啊 !
----------------解决方案--------------------------------------------------------
我试过是不一样的
先是左子树..当你-1时当前左子树结束..建立当前左子树的兄弟子树..要明确是怎么样结束就可以了  1 2 -1 -1 3 -1 -1 你看看呢
----------------解决方案--------------------------------------------------------
谢谢了。果然不一样,看来输入我还是不大了解。
----------------解决方案--------------------------------------------------------
  相关解决方案