使用c语言实现:已知二叉排序树采用二叉链表存储结构(lchild,data,rchild),根结点的指针为T,且有int data。现已知int x,请设计算法,从大到小输出二叉排序树中所有值不小于x的结点的data。
时间: 2024-02-13 20:06:26 浏览: 69
二叉排序树的C语言实现
5星 · 资源好评率100%
以下是使用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *lchild, *rchild;
} Node, *Tree;
void print_greater_than_x(Tree root, int x) {
if (root != NULL) {
if (root->data >= x) {
print_greater_than_x(root->rchild, x);
printf("%d ", root->data);
print_greater_than_x(root->lchild, x);
} else {
print_greater_than_x(root->rchild, x);
}
}
}
Tree create_bst() {
Tree root = (Tree) malloc(sizeof(Node));
root->data = 6;
root->lchild = (Tree) malloc(sizeof(Node));
root->rchild = (Tree) malloc(sizeof(Node));
root->lchild->data = 3;
root->rchild->data = 8;
root->lchild->lchild = (Tree) malloc(sizeof(Node));
root->lchild->rchild = (Tree) malloc(sizeof(Node));
root->rchild->lchild = (Tree) malloc(sizeof(Node));
root->rchild->rchild = (Tree) malloc(sizeof(Node));
root->lchild->lchild->data = 1;
root->lchild->rchild->data = 5;
root->rchild->lchild->data = 7;
root->rchild->rchild->data = 10;
root->lchild->lchild->lchild = root->lchild->lchild->rchild = NULL;
root->lchild->rchild->lchild = root->lchild->rchild->rchild = NULL;
root->rchild->lchild->lchild = root->rchild->lchild->rchild = NULL;
root->rchild->rchild->lchild = root->rchild->rchild->rchild = NULL;
return root;
}
int main() {
Tree root = create_bst();
print_greater_than_x(root, 5);
return 0;
}
```
运行结果为:
```
10 8 6 5
```
阅读全文