C语言搜索二叉树测试代码

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

typedef int DATA;
typedef struct _SNode_
{
    DATA data;
    struct _SNode_ *p_Right, *p_Left;
}SNode;

SNode *CreateTree(const DATA d)
{
    SNode *m_root = (SNode *)malloc(sizeof(SNode));
    m_root->data = d;
    m_root->p_Left = m_root->p_Right = NULL;
    return m_root;
}

void InsertRight(SNode *p, const DATA d)
{
    SNode *pNew = CreateTree(d);
    p->p_Right = pNew;
}

void InsertLeft(SNode *p, const DATA d)
{
    SNode *pNew = CreateTree(d);
    p->p_Left = pNew;
}

void PreOrder(SNode *p)
{
    printf("%d ", p->data);
    if (p->p_Left)
        PreOrder(p->p_Left);
    if (p->p_Right)
        PreOrder(p->p_Right);
}

void InOrder(SNode *p)
{
    if (p->p_Left)
        InOrder(p->p_Left);
    printf("%d ", p->data);
    if (p->p_Right)
        InOrder(p->p_Right);
}

void PostOrder(SNode *p)
{
    if (p->p_Left)
        PostOrder(p->p_Left);
    if (p->p_Right)
        PostOrder(p->p_Right);
    printf("%d ", p->data);
}

bool LookUp(SNode *p, const DATA d)
{
    while (p)
    {
        if (p->data == d)
            return true;
        else if (p->data > d)
            p = p->p_Left;
        else
            p = p->p_Right;
    }
    return false;
}

// 方式二:使用二级指针
void SetAt(SNode *p, const DATA d) // 创建搜索二叉树
{
    if (p == NULL)
    {
        p = CreateTree(d);
        return;
    }
    SNode **ppRoot = &p;
    while (*ppRoot)
    {
        if ((*ppRoot)->data < d)
            ppRoot = &(*ppRoot)->p_Right;
        else if ((*ppRoot)->data > d)
            ppRoot = &(*ppRoot)->p_Left;
    }
    SNode *pNew = CreateTree(d);
    *ppRoot = pNew;
}

int main()
{
    SNode *pRoot = CreateTree(30);
    SetAt(pRoot, 75);
    SetAt(pRoot, 20);
    SetAt(pRoot, 40);
    SetAt(pRoot, 10);
    SetAt(pRoot, 60);
    SetAt(pRoot, 50);

    if (LookUp(pRoot, 52))
        printf("找到了!\n");
    else
        printf("没有找到!\n");

    InOrder(pRoot);

    return 0;
}

相关推荐