【二叉树】--C语言实现创建二叉搜索树

二叉搜索树

创建二叉搜索树的过程很简单,第一个数字作为根,第二个数字,如果比根大,则作为根的右子树,如果比根小,则作为根的左子树。一次类推。对一棵二叉搜索树进行中序遍历,可以的到一个有序的序列。

代码

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

struct Node
{
    int data;
    struct Node *left;
    struct Node *right;
};
typedef struct Node Node;

Node *CreateBSTree(Node *root, int num)
{
    if (NULL == root)
    {
        root = (Node *)malloc(sizeof(Node) * 1);
        if (NULL == root)
        {
            return NULL;
        }
        root->data = num;
        root->left = NULL;
        root->right = NULL;
    }
    else
    {   
        if (root->data > num)
        {   
            root->left = CreateBSTree(root->left, num);
        }
        else
        {   
            root->right = CreateBSTree(root->right, num);
        }
    }

    return root;
}

void MidOrder(Node *root)
{
    if (NULL == root)
    {
        return;
    }

    MidOrder(root->left);
    printf("%d ", root->data);
    MidOrder(root->right);
}

int main()
{
    int i, num;
    Node *root = NULL;
    for (i = 0; i < 10; i++)
    {
        scanf("%d", &num);
        root = CreateBSTree(root, num);
    }

    MidOrder(root);
    printf("\n");
}

更多视频、文章、嵌入式学习资源,微信关注 【学益得智能硬件】

在这里插入图片描述

发布了33 篇原创文章 · 获赞 62 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/xiaopengX6/article/details/104900219