zoukankan      html  css  js  c++  java
  • 二叉排序树第一版

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

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

    #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
    */
  • 相关阅读:
    Linux基础-3.用户、群组和权限
    Linux基础-2.目录文件的浏览、管理及维护
    Linux基础-1.Linux命令及获取帮助
    CentOS6.10安装详解
    有序字典
    根据公历计算农历
    常用模块
    人工智能_2_特征处理.py
    人工智能_1_初识_机器学习介绍_特征工程和文本特征提取
    python-matplotlib
  • 原文地址:https://www.cnblogs.com/liboyan/p/4915971.html
Copyright © 2011-2022 走看看