haoyueting 于 2015.07.26 12:58 提问

`````` #include <iostream>
#include <fstream>
using namespace std;

class Node {
private:
int content;
Node *left;
Node *right;
public:
Node(int a);
~Node();
int getcontent();
Node *getleft();
Node *getright();
void setleft(Node *a);
void setright(Node *a);
};

Node::Node(int a):content(a), left(NULL), right(NULL){}

Node::~Node() {}

int Node::getcontent() {
return content;
}

Node * Node::getleft() {
return left;
}

Node * Node::getright() {
return right;
}

void Node::setleft(Node *a) {
this->left = a;
}

void Node::setright(Node *a) {
this ->right = a;
}

void insert(Node *pre, Node a) {
if (a.getcontent() < pre->getcontent()) {
if(pre->getleft() == NULL) {
pre->setleft(&a);
} else {
insert(pre->getleft(), a);
}
} else if (a.getcontent() >= pre->getcontent()){
if (pre->getright() == NULL) {
pre->setright(&a);
} else {
insert(pre->getright(), a);
}
}
return;
}

void print(Node *a) {
cout << a->getcontent() << " ";
if (a->getleft()->getcontent()) {
print(a->getleft());
}
if (a->getleft()->getcontent()) {
print(a->getright());
}
return;
}

int main() {
Node roof(5);
for (int i = 0; i < 10; ++i) {
int n;
cin >> n;
Node a(n);
insert(&roof, a);
}
print(&roof);
return 0;
}

``````

4个回答

devmiao      2015.07.26 14:28

caozhy      2015.07.26 14:35
``````整数对象a,please input 5 numbers
1 2 3 4 5 6 7 8 9 10

Press any key to continue
``````

VC++ 6.0，没有问题

caozhy 请忽略，答错了
2 年多之前 回复
caozhy      2015.07.26 14:50
`````` void print(Node *a) {
cout << a->getcontent() << " ";
if (a->getleft() == NULL) {
print(a->getleft());
}
if (a->getright() == NULL) {
print(a->getright());
}
return;
}

``````

CSDNword   2015.07.30 18:11