![](/img/trans.png)
[英]Why is the root variable in a Binary Tree a pointer the node and not the node itself?
[英]C++ Binary Tree, modifying root node, pointer to pointer to root node
我知道標題不太具描述性,因此以下是詳細信息。 我正在用C ++實現自己的Binary Tree類。 在大多數情況下,我已經編寫了一個模板Node類和模板Binary Tree類,並且停留在某些東西上。 我創建了一個空的二叉樹(根節點為null),當我嘗試設置該節點時,它會慘敗。 這是代碼和更多說明:
template<class T> class Node
{
T _key;
Node<T> *_leftChild;
Node<T> *_rightChild;
public:
Node();
Node(T key);
Node(T key, Node<T> *leftChild, Node<T> *rightChild);
~Node();
bool hasLeftChild();
bool hasRightChild();
void setKey(T key);
void setLeftChild(Node<T> *node);
void setRightChild(Node<T> *node);
T getKey();
Node<T>* getLeftChild();
Node<T>* getRightChild();
bool compare(Node<T> *compareNode); // return true if this.Node < compareNode
};
節點實現不是真正必要的..(我不認為)它很長。
#include "Node.cpp"
#include <iostream>
using namespace std;
template<class T> class BinaryTree
{
Node<T> *_root;
public:
BinaryTree();
BinaryTree(Node<T> *root);
~BinaryTree();
Node<T>* getRoot();
void insert(Node<T> **root, Node<T> *node);
};
template<class T>
BinaryTree<T>::BinaryTree()
{
this->_root = NULL;
}
template<class T>
BinaryTree<T>::BinaryTree(Node<T> *root)
{
this->_root = root;
}
template<class T>
BinaryTree<T>::~BinaryTree()
{
// delete stuff
}
template<class T>
Node<T>* BinaryTree<T>::getRoot()
{
return this->_root;
}
template<class T>
void BinaryTree<T>::insert(Node<T> **root, Node<T> *node)
{
if(!*root)
{
*root = node;
}
}
主要:
BinaryTree<int> *tree = new BinaryTree<int>();
Node<int> *root = tree->getRoot();
Node<int> **root1 = &root;
cout << tree->getRoot() << endl;
Node<int> *noChildrenNode = new Node<int>(2);
tree->insert(&root1, noChildrenNode);
cout << tree->getRoot() << endl;
插入當前功能只是為了將NULL根指針替換為作為參數傳入的節點指針。 可悲的失敗部分是,由於指針是一個副本,它實際上並未設置根節點。.但是我似乎無法弄清楚如何設置指向根節點的指針,以便可以對其進行更改。我必須親密接觸,任何幫助將不勝感激。
謝謝
首先,您必須包括所有錯誤消息的確切文本。 “慘敗”是不夠的。
我想你要
root = node;
不
*root = node;
因為如果root為null,則使用* root是null指針異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.