[英]Trying to create a pointer to parent node whilst building binary Tree
我是一個愛好者,對c ++很陌生,我正在努力實現這個樹的最佳方式。
我有很多問題,但主要是我試圖找出在構建樹期間存儲指向父節點的指針的最佳方法; 但是當我嘗試在preOrder
成員函數中訪問root->parent->data
preOrder
root->parent->data
值時,我收到了Bus錯誤 。 我可以愉快地訪問地址root->parent
,這輸出沒有錯誤。
任何人都可以在這里暗示我做的根本錯誤嗎? 我認為它可能是一個范圍問題,但可能有更好的方法來構建樹?
class FibTree {
class Node {
public:
int data;
Node const* left;
Node const* right;
Node const* parent;
Node (void);
};
Node const* root; // 'root' pointer to constant Node
public:
FibTree (int);
Node const* getRoot(void);
void preOrder(Node const* root);
};
// Tree constructor
FibTree::FibTree(int n) {
this->root = buildTree( n );
};
FibTree::Node const* FibTree::getRoot(void) {
return this->root;
}
private:
static Node* buildTree( int n, Node* parent = NULL );
};
void FibTree::preOrder(Node const* root) {
if (root == NULL)
return;
// *** This prints the address of the parent node correctly
cout << root->data << "[" << root->parent << "]" << ",";
// *** This produces a 'Bus Error'
cout << root->data << "[" << root->parent->data << "]" << ",";
preOrder(root->left);
preOrder(root->right);
}
FibTree::Node* FibTree::buildTree( int n, Node* parent ) {
// *** Is there a scope issue with 'thisNode' here?
Node* thisNode = new Node();
thisNode->parent = parent;
if (n < 2) {
thisNode->left = NULL;
thisNode->right = NULL;
thisNode->data = n;
return thisNode;
} else {
thisNode->left = buildTree( n - 1 , thisNode );
thisNode->right = buildTree( n - 2, thisNode );
thisNode->data = thisNode->left->data + thisNode->right->data;
return thisNode;
}
}
// Node constructor
FibTree::Node::Node(void) {
this->data;
this->left;
this->right;
this->parent;
};
int main () {
FibTree f(n);
f.preOrder(f.getRoot());
return 0;
}
另外,會有用於避免具有與傳遞的標准方法root
節點至穿越功能,並具有成員函數,遍歷創建root
節點。 因為我覺得f.preOrder(f.getRoot())
非常優雅。
非常感謝,Alex
據我所知,問題是:
你的buildTree
函數中的這一行,
thisNode->parent = parent;
這個功能,
// Tree constructor
FibTree::FibTree(int n) {
this->root = buildTree( n );
};
和你的preOrder
功能。
父指針未在樹構造函數中傳遞給buildTree,因此默認值為NULL指針。 所以root-> parent將為NULL(有意義,因為它是根)。
然后從root用戶開始調用preOrder
函數。 Root有一個NULL的parent
,但是你從不檢查它(你確實檢查root本身是否為NULL)。
您應該執行以下操作:
void FibTree::preOrder(Node const* root) {
if (root == NULL)
return;
if(root->parent == NULL) {
cout << root->data << " [I am the root] " << endl;
}
else {
cout << root->data << "[" << root->parent->data << "]" << ",";
}
preOrder(root->left);
preOrder(root->right);
}
我無法重現這個問題,但看起來最可疑的部分是這樣的:
// Node constructor
FibTree::Node::Node(void) {
this->data;
this->left;
this->right;
this->parent;
};
語句( this->data
)絕對沒有。 也許你想要(並且應該嘗試):
FibTree::Node::Node()
: data( 0 ),
left( NULL ),
right( NULL ),
parent( NULL )
{
}
解釋:您的代碼沒有初始化數據和指針,因此它們未初始化。 如果您打印指針,通常可以工作,但取消引用它可能會導致您看到的錯誤。
執行此操作時,您可能會看到parent
變為NULL
並且您需要檢查它:
if( root->parent != NULL ) {
cout << root->data << "[" << root->parent->data << "]" << ",";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.