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

    题目截图:

    思路:

      二叉排序树的操作详解请看另一篇博客

    代码如下:

     1 /*
     2     二叉排序树 
     3 */
     4 
     5 #include <stdio.h>
     6 #include <string.h>
     7 #include <math.h>
     8 #include <stdlib.h>
     9 #include <time.h>
    10 #include <stdbool.h>
    11 
    12 // 二叉树结构体定义 
    13 typedef struct _node {
    14     int data;
    15     struct _node *lchild, *rchild;
    16 } node;
    17 
    18 // 二叉排序树插入结点 x 
    19 void insert(node** root, int x) {
    20     if(*root == NULL) {                    // 若为空树,即为插入位置
    21         // 新建结点 
    22         node* p = (node*)malloc(sizeof(node));
    23         p->data = x;    
    24         p->lchild = p->rchild = NULL;
    25         (*root) = p;                    // 插入新结点 
    26         return;
    27     }
    28     if(x == (*root)->data) {            // 重复节点,不处理 
    29         return;
    30     } else if(x < (*root)->data) {        // 小于根结点权值 
    31         insert(&(*root)->lchild, x);    // 插入到左子树 
    32     } else {                            // 大于根结点权值 
    33         insert(&(*root)->rchild, x);    // 插入到右子树 
    34     }
    35 }
    36 
    37 // 先序遍历 
    38 void preorder(node* root) {
    39     if(root == NULL) {
    40         return;
    41     }
    42     printf("%d ", root->data);
    43     preorder(root->lchild);
    44     preorder(root->rchild);
    45 }
    46 
    47 // 中序遍历 
    48 void inorder(node* root) {
    49     if(root == NULL) {
    50         return;
    51     }    
    52     inorder(root->lchild);
    53     printf("%d ", root->data);
    54     inorder(root->rchild);
    55 }
    56 
    57 // 后续遍历 
    58 void postorder(node* root) {
    59     if(root == NULL) {
    60         return;
    61     }    
    62     postorder(root->lchild);
    63     postorder(root->rchild);
    64     printf("%d ", root->data);
    65 }
    66 
    67 int main() {
    68     int n;
    69     while(scanf("%d", &n) != EOF) {
    70         int i;
    71         node* root = NULL;
    72         for(i=0; i<n; ++i) {
    73             int x;
    74             scanf("%d", &x);    // 输入数据 
    75             insert(&root, x);    // 插入结点 
    76         }
    77         preorder(root);            // 输出前序序列 
    78         printf("
    ");
    79         inorder(root);            // 输出中序序列
    80         printf("
    ");
    81         postorder(root);        // 输出后序序列
    82         printf("
    ");
    83     }
    84 
    85     return 0;
    86 }
  • 相关阅读:
    Editor REST Client
    log配置
    spring-boot-configuration-processor
    http请求
    做项目用到的一些正则表达式,贴出来共享
    批量插入的实现
    sql执行顺序对比
    Java常用的并发工具类:CountDownLatch、CyclicBarrier、Semaphore、Exchanger
    spring中bean的生命周期
    多属性的对象列表的两种排序方法
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest20.html
Copyright © 2011-2022 走看看