zl程序教程

您现在的位置是:首页 >  其他

当前栏目

c语言根据数组创建二叉排序树

语言数组排序 创建 根据 二叉
2023-09-14 09:06:52 时间

c语言创建二叉排序树

二叉排序树(Binary Sort Tree),又称二叉查找树(Binary Search Tree),亦称二叉搜索树。是数据结构中的一类。在一般情况下,查询效率比链表结构要高。

博主写了一个根据数组一次循环遍历就可以创建一个二叉排序树,比较不同的是,我们使用的二级指针去做的创建二叉排序树,非常方便,

struct tree{
    int val;
    int count;
    struct tree *right;
    struct tree *left;

};

void add_tree(struct tree **root,int val,int count){
    if((*root)==NULL){
        struct tree* node=(struct tree*)malloc(sizeof(struct tree));
        node->val=val;
        node->left=NULL;
        node->right=NULL;
        node->count=count;
        (*root)=node;
    }
    else{

        if((*root)->val==val){
            (*root)->count++;
        }
        else{
            if((*root)->val>val){
                (*root)->count++;

                add_tree(&((*root)->left),val,count);
            }
            else{
                 add_tree(&((*root)->right),val,(*root)->count+1);

            }
        }
    }
}





void print_tree(struct tree *root){
    if(root){
        print_tree(root->left);
        printf("%d %d -- ",root->val,root->count);
          print_tree(root->right);
    }
}





int reversePairs(int* nums, int numsSize){
    struct tree *root=NULL;
   
    
    for(int i=0;i<numsSize;i++){
        add_tree(&root,nums[i],0);
      
       // printf("%d |",nums[i]);
        }
        print_tree(root);

    return 0;

}