题解 | #二叉排序树#
二叉排序树
https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node {
int val;
struct node* left, *right;
}* bittree, node;
bittree build(bittree& t, bittree node) {
if (t == NULL) {
return node;
}
if (t->val > node->val) {
t->left = build(t->left, node);
} else if (t->val < node->val) {
t->right = build(t->right, node);
}
return t;
}
void prepost(bittree t) {
if (t != NULL) {
cout << t->val << " ";
prepost(t->left);
prepost(t->right);
}
}
void midpost(bittree t) {
if (t != NULL) {
midpost(t->left);
cout << t->val << " ";
midpost(t->right);
}
}
void postpost(bittree t) {
if (t != NULL) {
postpost(t->left);
postpost(t->right);
cout << t->val << " ";
}
}
int main() {
int n;
while(cin >> n){
int temp;
bittree t = NULL;
for (int i = 0; i < n; i++) {
cin >> temp;
bittree t_node = (bittree)malloc(sizeof(node));
t_node->val = temp;
t_node->left = NULL;
t_node->right = NULL;
t = build(t, t_node);
}
prepost(t);
cout << endl;
midpost(t);
cout << endl;
postpost(t);
cout << endl;
}
return 0;
}
