题解 | #二叉排序树#
二叉排序树
https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3
#include<iostream>
#include<cstring>
using namespace std;
int arr[101];
typedef struct BiTNode {
int data;
struct BiTNode* L, * R;
}BiTNode, * BiTree;
void Insert_Bitree(BiTree & root, int k) {
if (root == NULL) {
root = (BiTNode*)malloc(sizeof(BiTNode));
root->data = k;
root->L = NULL;
root->R = NULL;
}
else if (root->data == k) {
return;
}
else if (root->data > k) {
Insert_Bitree(root->L, k);
}
else {
Insert_Bitree(root->R, k);
}
}
void Pre_Order(BiTree& T) {
if (T != NULL) {
cout << T->data << " ";
Pre_Order(T->L);
Pre_Order(T->R);
}
return;
}
void In_Order(BiTree& T) {
if (T != NULL) {
In_Order(T->L);
cout << T->data << " ";
In_Order(T->R);
}
return;
}
void Post_Order(BiTree& T) {
if (T != NULL) {
Post_Order(T->L);
Post_Order(T->R);
cout << T->data << " ";
}
return;
}
int main() {
int n;
while (cin >> n && n) {
memset(arr, 0, 101);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
BiTree T=NULL;
for (int i = 0; i < n; i++) {
Insert_Bitree(T, arr[i]);
}
Pre_Order(T);
cout << endl;
In_Order(T);
cout<<endl;
Post_Order(T);
cout<<endl;
}
}

查看7道真题和解析