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
    */
  • 相关阅读:
    Leetcode 15 3Sum
    Leetcode 383 Ransom Note
    用i个点组成高度为不超过j的二叉树的数量。
    配对问题 小于10 1.3.5
    字符矩阵的旋转 镜面对称 1.2.2
    字符串统计 连续的某个字符的数量 1.1.4
    USACO twofive 没理解
    1002 All Roads Lead to Rome
    USACO 5.5.1 求矩形并的周长
    USACO 5.5.2 字符串的最小表示法
  • 原文地址:https://www.cnblogs.com/liboyan/p/4915971.html
Copyright © 2011-2022 走看看