[英]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.