我有一个二叉树,其节点被定义为段落设置布尔可能吗?
typedef unsigned long ul;
struct Fibonacci_node{
ul number;
int n;
bool isLeaf;
Fibonacci_node * left;
Fibonacci_node * right;
};
我想设置isLeaf
每次插入,这样我就可以很容易地得到叶子的总数最终。插入方法由公共方法插入构成,该方法调用专用递归方法insertR。
#include <iostream>
using namespace std;
class Fibonacci_tree{
private:
struct Fibonacci_node{
ul number; // store the n-th fibonacci number
int n; // fibonacci number to compute
bool isLeaf; // true if the node is leaf
Fibonacci_node * left;
Fibonacci_node * right;
};
/* definition of the root of the binary tree */
Fibonacci_node * root;
/* class private methods (recursively defined) */
ul fibonacci(int n){
/* BASE CASE */
if (n == 0) { return 1; }
if (n == 1) { return 1; }
/* call the function recursively */
return fibonacci(n - 1) + fibonacci(n - 2);
};
Fibonacci_node * insertR(int n, Fibonacci_node * node){
if (!node) {
/* if pointer is null create a new node */
Fibonacci_node * tmp = new Fibonacci_node;
tmp->n = n;
tmp->number = fibonacci(tmp->n);
tmp->left = tmp->right = 0;
tmp->isLeaf = 0;
/* update the pointer and return it */
node = tmp;
/* BASE CASE */
if (n == 0) {
node->isLeaf = 1;
return node;
}
if (n == 1) {
node->isLeaf = 1;
return node;
}
}
/* call the function recursively */
node->left = insertR(n - 1, node->left);
node->right = insertR(n - 2, node->right);
return node;
};
public:
Fibonacci_tree(){
root = 0;
}
~Fibonacci_tree(){}
/* class public methods (they include private methods recursively defined)*/
void insert(int n){
/* first, create initial node and compute fibonacci for the root */
Fibonacci_node * tmp = new Fibonacci_node;
tmp->n = n;
tmp->number = fibonacci(n);
tmp->isLeaf = false;
//getNo(tmp);
/* make root point to the first element of the tree */
root = tmp;
/* then call the recursive function */
root = insertR(n, root);
};
};
/* END OF CLASS DECLARATION */
/* main program to check the class */
int main(void) {
int n = 3;
/* instantiate a Fibonacci tree */
Fibonacci_tree fib_series;
/* fill the tree */
fib_series.insert(n);
return 0;
}
当我运行我的可执行文件,我得到
Segmentation fault: 11
我打印过的若干意见,我注意到,错误似乎后立即出现在我指定“假”的布尔值。所以,我假设分配出错了,但这是我在这种情况下第一次出现分段错误。
我也认为,因为到目前为止我没有任何问题,但是这个,它开始时,我在类定义中引入此变量。
是否有可能因此而导致分段错误,或者我可能在其他地方有问题,我还没有注意到呢?
我想完全调试它自己,但我的调试技巧仍然有点尴尬。因此,任何反馈真的很感激。
这个tmp来自哪里? – SergeyA
你可能认为你在设置isLeaf,但是如果tmp是一个指针而不是斐波那契数组的实例,但是对于一些随机存储器,你正在做一些非常令人讨厌的事情来覆盖你不应该的东西,所以,不,设置一个bool不能成立的原因segfault,但随机写入内存可能在长期运行可以。 –
请给我们看[mcve]。 –