二叉排序树第一版

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

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

#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
*/
原文地址:https://www.cnblogs.com/liboyan/p/4915971.html