二叉排序树

题目截图:

 

 

思路:

   参照我的另一篇博客

 

 

代码如下:

 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* left;        // 左子树 
16     struct _node* right;    // 右子树 
17 } node; 
18 
19 // 在以 root 为根结点中插入结点 x,pre 储存父结点 
20 void insert(node** root, node* pre, int x) {
21     if((*root) == NULL) {    // 若根结点为空,表示已经找到插入位置 
22         // 新建结点 
23         node* newNode = (node*)malloc(sizeof(node));
24         newNode->data = x;
25         newNode->left = newNode->right = NULL;
26         (*root) = newNode;    // 插入结点 
27         if(pre == NULL) {    // 输出父结点 
28             printf("-1"); 
29         } else {
30             printf("%d", pre->data);
31         }
32         return;
33     }
34     if(x == (*root)->data) {    // 树中已经有该结点 
35         return;
36     } else if(x < (*root)->data) {    // 值小于根结点的值,应插到左子树 
37         insert(&(*root)->left, *root, x);
38     } else {                        // 值大于根结点的值,应插到右子树 
39         insert(&(*root)->right, *root, x);
40     }
41 }
42 
43 int main() {
44     int N, i, x;
45     scanf("%d", &N);            // 结点个数 
46     node* root = NULL;
47     for(i=0; i<N; ++i) {
48         scanf("%d", &x);
49         insert(&root, root, x);    // 插入结点 
50         if(i != N-1) {            // 格式化输出 
51             printf("\n");
52         }
53     }
54 
55     return 0;
56 }

 

posted @ 2018-02-05 17:04  Just_for_Myself  阅读(251)  评论(0编辑  收藏  举报