#include <stdlib.h>
#include <iostream>
#include<sstream>
using namespace std;
typedef struct node *Nodeptr;
typedef struct node {
int val;
Nodeptr left;
Nodeptr right;
} Node;
Node *addtree(Node *tree, double val);
void preorder(Node *tree);
Node *talloc(void);
void inorder(Node *tree);
void postorder(Node *tree);
int main() {
string s;
while (getline(cin,s) ){
stringstream ss;
ss<<s;
Node *root = NULL;
double n;
while(ss>>n){
root = addtree(root, n);
}
string d;
cin>>d;
if(d=="pre"){
preorder(root);
}
if(d=="in"){
inorder(root);
}
if(d=="post"){
postorder(root);
}
cout << endl;
}
return 0;
}
Node *addtree(Node *tree, double val) {
if (tree == NULL) {
tree = talloc();
tree->val = val;
tree->left = NULL;
tree->right = NULL;
} else if (val < tree->val)
tree->left = addtree(tree->left, val);
else
tree->right = addtree(tree->right, val);
return tree;
}
void preorder(Node *tree) {
cout<<tree->val<<' ';
if(tree->left)preorder(tree->left);
if(tree->right)preorder(tree->right);
}
void inorder(Node *tree){
if(tree->left)inorder(tree->left);
cout<<tree->val<<' ';
if(tree->right)inorder(tree->right);
}
void postorder(Node *tree){
if(tree->left) preorder(tree->left);
if(tree->right)preorder(tree->right);
cout<<tree->val<<' ';
}
Node *talloc(void) {
return (Node *) malloc(sizeof(struct node));
}
以上NA40%,請大神幫幫我
#include
#include
#include
using namespace std;
typedef struct node *Nodeptr;
typedef struct node {
int val;
Nodeptr left;
Nodeptr right;
} Node;
Node *addtree(Node *tree, double val);
void preorder(Node *tree);
Node *talloc(void);
void inorder(Node *tree);
void postorder(Node *tree);
int main() {
string s;
while (getline(cin,s) ){
stringstream ss;
ss<<s;
Node *root = NULL;
double n;
while(ss>>n){
root = addtree(root, n);
}
string d;
cin>>d;
if(d=="pre"){
preorder(root);
}
if(d=="in"){
inorder(root);
}
if(d=="post"){
postorder(root);
}
cout << endl;
}
return 0;
}
Node *addtree(Node *tree, double val) {
if (tree == NULL) {
tree = talloc();
tree->val = val;
tree->left = NULL;
tree->right = NULL;
} else if (val < tree->val)
tree->left = addtree(tree->left, val);
else
tree->right = addtree(tree->right, val);
return tree;
}
void preorder(Node *tree) {
cout<val<<' ';
if(tree->left)preorder(tree->left);
if(tree->right)preorder(tree->right);
}
void inorder(Node *tree){
if(tree->left)inorder(tree->left);
cout<val<<' ';
if(tree->right)inorder(tree->right);
}
void postorder(Node *tree){
if(tree->left) preorder(tree->left);
if(tree->right)preorder(tree->right);
cout<val<<' ';
}
Node *talloc(void) {
return (Node *) malloc(sizeof(struct node));
}
以上NA40%,請大神幫幫我
不用了,謝謝