• 【数据结构】——排序二叉树


      排序二叉树即在构建二叉树的时候就对二叉树进行排序了,当中序遍历二叉树的时候即可得到一个有序的数列;

      排序二叉树的规则就是:

      若他的左子树不空,则左子树上所有结点的值均小于它的根结构的值;

      若他的右子树不空,则右子树上所有结点的值均大于它的根结点的值;

      它的左、右子树也分别为二叉排序树;

      从二叉排序树的定义也可以知道,它前提是二叉树,然后它采用了递归的定义方法,再者,它的结点间满足一定得次序关系,左子树结点一定比其双亲结点小,右子树结点一定比其双亲结点打。

      代码实现如下:

     1 void Create_Sort_Tree(BiTree **t, int value)
     2 {
     3     if(*t == NULL){
     4         *t = (BiTree *)malloc(sizeof(BiTree));
     5         (*t)->item = value;
     6         (*t)->lchild = NULL;
     7         (*t)->rchild = NULL;
     8     }
     9     else{
    10         if((*t)->item > value)
    11             Create_Sort_Tree(&(*t)->lchild, value);
    12         else
    13             Create_Sort_Tree(&(*t)->rchild, value);    
    14     }
    15 }

      用递归的思想,在创建的时候即排序;

      完整实例如下:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 typedef struct BiTree{
     5     int item;
     6     struct BiTree *lchild,*rchild;
     7 }BiTree;
     8 
     9 void Create_Sort_Tree(BiTree **t, int value)
    10 {
    11     if(*t == NULL){
    12         *t = (BiTree *)malloc(sizeof(BiTree));
    13         (*t)->item = value;
    14         (*t)->lchild = NULL;
    15         (*t)->rchild = NULL;
    16     }
    17     else{
    18         if((*t)->item > value)
    19             Create_Sort_Tree(&(*t)->lchild, value);
    20         else
    21             Create_Sort_Tree(&(*t)->rchild, value);    
    22     }
    23 }
    24 
    25 void lar(BiTree *t)
    26 {
    27     if(t == NULL)
    28         return;
    29     else{
    30         lar(t->lchild);
    31         printf("%d	",t->item);
    32         lar(t->rchild);
    33     }
    34         
    35 }
    36 
    37 int main(void)
    38 {
    39     int i;
    40     BiTree *t = NULL;
    41     int value[] = {5,8,14,36,21,1,3};
    42     for(i = 0;i < 7;i++)
    43         Create_Sort_Tree(&t,value[i]);    
    44     lar(t);
    45     printf("
    ");
    46 }
  • 相关阅读:
    vscode 基本知识以及如何配置 C++ 环境
    计算机视觉
    GitHub 大事件
    tf 2.0
    AI 公司与比赛
    Faster RCNN 学习与实现
    pycahrm安装说明
    python 并发之线程
    python 并发之进程
    python socketserver ftp上传功能
  • 原文地址:https://www.cnblogs.com/ngnetboy/p/3161758.html
Copyright © 2020-2023  润新知