基于二叉排序树的限定条件下的数据输出

给定x的值和一组数据,通过二叉排序树从小到大输出大于x的所有值。

输入样例:
5
1 5 3 2 4
3
9
1 30 2 15 6 7 3 9 233
30
0

输出样例:
3 4 5
30 233

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MaxSize 100

typedef struct BiTNode {
    
    
    int data;
    struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;

bool BSTInsert(BiTree *root, int data);
void BSTInit(BiTree *root, int *nodeData, int n);
void BSTDestroy(BiTree *root);

void showData(BiTree root, int x, int *cursor, int *arr) {
    
    
    if (root) {
    
    
        showData(root->lchild, x, cursor, arr);
        if (root->data >= x) {
    
    
            arr[*cursor] = root->data;
            (*cursor)++;
        }
        showData(root->rchild, x, cursor, arr);
    }
}

int main() {
    
    
    int n;

    while (scanf("%d%*c", &n) && n != 0) {
    
    
        BiTree T;
        int nodeData[MaxSize];
        int x, cursor = 0, arr[MaxSize];

        for (int i = 0; i < n; i++) {
    
    
            scanf("%d%*c", nodeData + i);
        }
        scanf("%d%*c", &x);

        BSTInit(&T, nodeData, n);
        showData(T, x, &cursor, arr);
        for (int i = 0; i < cursor; i++) {
    
    
            printf("%d%c", arr[i], i == cursor - 1 ? 10 : 32);
        }
        BSTDestroy(&T);
    }
    return 0;
}

bool BSTInsert(BiTree *root, int key) {
    
    
    if (!*root) {
    
    
        *root = (BiTNode *) malloc(sizeof(BiTNode));
        (*root)->data = key;
        (*root)->lchild = (*root)->rchild = NULL;
        return true;
    } else if ((*root)->data > key) {
    
    
        return BSTInsert(&(*root)->lchild, key);
    } else if ((*root)->data < key) {
    
    
        return BSTInsert(&(*root)->rchild, key);
    } else {
    
    //(*root)->data == key
        return false;
    }
}

void BSTInit(BiTree *root, int *nodeData, int n) {
    
    
    *root = NULL;
    int i = 0;

    while (i < n) BSTInsert(root, nodeData[i++]);
}

void BSTDestroy(BiTree *root) {
    
    
    if (*root) {
    
    
        BSTDestroy(&(*root)->lchild);
        BSTDestroy(&(*root)->rchild);
        free(*root);
        *root = NULL;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43686863/article/details/123642715