#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct TreeNode {
int data;
struct TreeNode *left,*right;
};
void preOrder(TreeNode *root) {
if(root != NULL) {
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode *root) {
if(root != NULL) {
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
}
void postOrder(TreeNode *root) {
if(root != NULL) {
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
}
void insertBST(TreeNode* &root,int data) {
if(root == NULL) {
root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = data;
root->left = NULL;
root->right = NULL;
return;
} else if(root->data > data) {
insertBST(root->left,data);
} else if(root->data < data) {
insertBST(root->right,data);
}
}
int main() {
int n = 0;
while(cin>>n) {
TreeNode* p = NULL;
for(int i = 0 ; i < n; i++) {
int input = 0;
cin>>input;
insertBST(p,input);
}
preOrder(p);
cout<<endl;
inOrder(p);
cout<<endl;
postOrder(p);
cout<<endl;
}
return 0;
}
1、可能有多组测试数据的时候 输入一定要写为 while(cin>>n)!

京公网安备 11010502036488号