首页 新闻 会员 周边

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

0
悬赏园豆:20 [已解决问题] 解决于 2015-07-27 09:18

本人小白,写了个简单的二叉树练习一下,代码如下,运行时会出现segmentation fault :11错误,求助各位大大帮忙看看是什么原因?

 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 }

c++
黑巧书生的主页 黑巧书生 | 初学一级 | 园豆:184
提问于:2015-07-26 12:12
< >
分享
最佳答案
0

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

setright同理。

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

收获园豆:20
我是一只C++小小鸟 | 菜鸟二级 |园豆:226 | 2015-07-26 16:34

谢谢,感谢启发,后来重新写了。

开始没写Tree 类。

黑巧书生 | 园豆:184 (初学一级) | 2015-07-27 09:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册