我有一個二叉樹,其節點被定義爲段落設置布爾可能嗎?
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]。 –