学会利用递归思想来建立排序树
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode {
int data;
TreeNode* leftchild;
TreeNode* rightchild;
};
TreeNode* BuildTree(TreeNode* & root, int n) { //建立排序树
if (root == NULL)
{
root = new TreeNode;
root->data = n;
root->leftchild = NULL;
root->rightchild = NULL;
}
else if (n < root->data) {
root->leftchild = BuildTree(root->leftchild, n);
}
else if (n > root->data) {
root->rightchild = BuildTree(root->rightchild, n);
}
return root;
}
void Preorder(TreeNode* t) {
if (t == NULL) return;
else {
cout << t->data << ' ';
Preorder(t->leftchild);
Preorder(t->rightchild);
}
}
void Inorder(TreeNode* t) {
if (t == NULL) return;
else {
Inorder(t->leftchild);
cout << t->data << ' ';
Inorder(t->rightchild);
}
}
void Postorder(TreeNode* t) {
if (t == NULL) return;
else {
Postorder(t->leftchild);
Postorder(t->rightchild);
cout << t->data << ' ';
}
}
int main() {
int n;
int num[100];
while (cin >> n) {
TreeNode* root = NULL;
for (int i = 0; i < n; i++) {
cin >> num[i];
BuildTree(root, num[i]);
}
Preorder(root);
cout << endl;
Inorder(root);
cout << endl;
Postorder(root);
cout << endl;
}
}