二叉排序树第一版

       二叉排序树的建树顺序(规则)是   左<根<右,缺点很明显,树的深度不一,极端情况可能左空右满,反之也一样,这也就是说这棵树随时可能退化成表。找最小值要把根节点的左子树全部遍历一遍,最大值同理。目前没发现有什么用处,不过这是平衡二叉树的基础,所以就写了一版,销毁函数就不写了。

       不对请指正。下一版就是平衡二叉树。

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;
typedef int type;

struct tree
{
    type data;
    tree *left,*right;
}*root;
void insert1(tree *node,int a)
{
    tree *temp;
    if(node->data > a)
    {
        if(node->left == NULL)
        {
            temp = new tree;
            if(temp == NULL)
            {
                puts("fail");
                return;
            }
            temp->data = a;
            temp->left = temp->right = NULL;
            node->left = temp;
        }
        else
        {
            insert1(node->left,a);
        }
    }
    else
    {
        if(node->right == NULL)
        {
            temp = new tree;
            if(temp == NULL)
            {
                puts("fail");
                return;
            }
            temp->data = a;
            temp->left = temp->right = NULL;
            node->right = temp;
        }
        else
        {
            insert1(node->right,a);
        }
    }
}
void M_ergodic(tree *node)   //  中序遍历  从大到小输出
{
    if(node->left != NULL) M_ergodic(node->left);
    printf("%d ",node->data);
    if(node->right != NULL) M_ergodic(node->right);
}
int main()
{
    root = new tree;
    root->left=NULL;
    root->right=NULL;
    if(root == NULL)
    {
        puts("fail");
    }
    int a;
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a);
        if(i==0)
        {
            root->data=a;
        }
        else insert1(root,a);
    }
    M_ergodic(root);
    puts("");
    return 0;
}

/*
10
8 9 1 15 10 3 2 4 6 10
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值