【发布时间】:2013-03-14 00:23:54
【问题描述】:
作为个人项目的一部分,而不是家庭作业 - 只是为了我自己的兴趣和 C++ 入门,我正在尝试创建一个斐波那契值的二叉树; 我知道我在这里犯了一些基本错误,但如果有人可以帮助我,我将不胜感激,我的代码如下:
#include <iostream>
#include <typeinfo>
using namespace std;
class FibTree {
class Node {
public:
Node const* left;
Node const* right;
int value;
Node (int, Node*, Node*);
};
Node const* root;
public:
FibTree (int);
int getValue(){
return this->root->value;
};
private:
static Node* buildTree(int n ) {
if (n < 2) {
return new Node( n, NULL, NULL );
} else {
Node* left = buildTree( n - 1 );
Node* right = buildTree( n - 2 );
return new Node( left->value + right->value , left, right );
}
}
};
FibTree::FibTree(int n) {
this->root = buildTree(n);
};
FibTree::Node::Node(int value, Node* left, Node* right){
this->value = value;
this->left = left;
this->right = right;
};
int main () {
FibTree f(6);
cout << f.getValue();
return 0;
}
谁能让我知道我在这里做错了什么,重要的是告诉我为什么我会收到错误'Cannot convert 'FibTree' to 'FibTree*' in assignment;以及我应该如何更好地处理?
提前致谢, 亚历克斯
【问题讨论】:
-
整个实现是错误的;你需要从头开始重写代码。
-
this->left = new FibTree(n - 1, this);是您修复错误的方法(以换取一些内存泄漏,但它们不会造成伤害)。但我同意你的看法:你犯了一堆根本性的错误。但我会把它留给希望构建完整答案的人:)
标签: c++ data-structures recursion binary-tree fibonacci