# 写一个简单的二叉树遇到了segmentation fault :11问题，求助

0

``` 1 #include <iostream>
2 #include <fstream>
3 using namespace std;
4
5 class Node {
6 private:
7     int content;
8     Node *left;
9     Node *right;
10 public:
11     Node(int a);
12     ~Node();
13     int getcontent();
14     Node *getleft();
15     Node *getright();
16     void setleft(Node *a);
17     void setright(Node *a);
18 };
19
20 Node::Node(int a):content(a), left(NULL), right(NULL){}
21
22 Node::~Node() {}
23
24 int Node::getcontent() {
25     return content;
26 }
27
28 Node * Node::getleft() {
29     return left;
30 }
31
32 Node * Node::getright() {
33     return right;
34 }
35
36 void Node::setleft(Node *a) {
37     this->left = a;
38 }
39
40 void Node::setright(Node *a) {
41     this ->right = a;
42 }
43
44 void insert(Node *pre, Node a) {
45     if (a.getcontent() < pre->getcontent()) {
46         if(pre->getleft() == NULL) {
47             pre->setleft(&a);
48         } else {
49             insert(pre->getleft(), a);
50         }
51     } else if (a.getcontent() >= pre->getcontent()){
52         if (pre->getright() == NULL) {
53             pre->setright(&a);
54         } else {
55             insert(pre->getright(), a);
56         }
57     }
58     return;
59 }
60
61 void print(Node *a) {
62     cout << a->getcontent() << " ";
63     if (a->getleft()->getcontent()) {
64         print(a->getleft());
65     }
66     if (a->getleft()->getcontent()) {
67         print(a->getright());
68     }
69     return;
70 }
71
72 int main() {
73     Node roof(5);
74     for (int i = 0; i < 10; ++i) {
75         int n;
76         cin >> n;
77         Node a(n);
78         insert(&roof, a);
79     }
80     print(&roof);
81     return 0;
82 }```

0

insert() 函数中把pre->setleft(&a); 改成 pre->setledt(new Node(a));

setright同理。

print()中要先判断结点是不是NULL

您需要登录以后才能回答，未注册用户请先注册