BST在C中遍历

时间:2015-02-16 14:20:31

标签: c binary-search-tree tree-traversal

使用C遍历树。它将接受一个字符并打印修复后/修复/预修复。 问题是当它打印输出它看起来像这个

 input
 a
 b
 c
 d
 e
 f
 g
 h
 i   
    IN ORDER:   C abcdefghi
    PRE ORDER:  C  abcdefghi
    POST ORDER:  ihgfedcba C

当我遍历并且前后顺序错误时,有空格和字符'C'。我不知道出了什么问题。我在输入输入时错了吗?使用scanf获取char的地址? 这是整个代码

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>



typedef struct BST
{
    char data;
    struct BST *lchild, *rchild;
}node;

node *get_node()
{
    node *temp;
    temp=(node *)malloc(sizeof(node));
    temp->lchild=NULL;
    temp->rchild=NULL;
    return temp;
}

void insert(node *root, node *new_node)
{
    if((new_node->data) < (root->data))
    {
            if((root->lchild)==NULL)
            {
                root->lchild=new_node;
            }
            else
            {
                insert(root->lchild,new_node);
            }

    }

    if(new_node->data > root->data)
    {
        if((root->rchild)==NULL)
        {
            root->rchild=new_node;
        }
        else
        {
            insert(root->rchild,new_node);
        }
    }
}

void inorder(node *temp)
{
    if(temp!=NULL)
    {
        inorder(temp->lchild);
        putchar(temp->data);
        inorder(temp->rchild);
    }
}

void preorder(node *temp)
{
    if(temp!=NULL)
    {

            putchar(temp->data);
            preorder(temp->lchild);
            preorder(temp->rchild);

    }
}

void postorder(node *temp)
{
    if(temp!=NULL)
    {
        postorder(temp->lchild);
        postorder(temp->rchild);
        putchar(temp->data);

    }

}

void main()
{
    int i;
    node *new_node, *root, *tmp, *parent;
    node *get_node();
    char c;
    clrscr();

    for(i=0;i<9;i++)
    {
        fflush(stdin);

        new_node=get_node();


        printf("\nenter element: ");
        scanf("%c", &new_node->data);

        if(root==NULL)
        {
            root = new_node;
        }   
        else
        {
            insert(root, new_node);
        }

    }

    printf("\n\nIN ORDER: ");
    inorder(root);
    printf("\nPRE ORDER: ");
    preorder(root);
    printf("\nPOST ORDER: ");
    postorder(root);




    getch();
}

1 个答案:

答案 0 :(得分:0)

  

我遍历时有空格和字符'C'

这很可能是由于Joachim Pileborg注意到root缺少初始化所致。

  

前后订单错误

他们不是;除了空间和'C'之外,你还有退化(或病态)树

                a
                 \
                  b
                   \
                    c
                     \
                      d
                       \
                        e
                         \
                          f
                           \
                            g
                             \
                              h
                               \
                                i
输出订单正确无误。