ITPub博客

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

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

作者:ofan 时间:2019-09-20 10:02:36 0 删除 编辑

本人小白,写了个简单的二叉树练习一下,代码如下,运行时会出现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 }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4571/viewspace-3159333/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-01

  • 博文量
    159
  • 访问量
    1161