[英]C++ Binary Tree, modifying root node, pointer to pointer to root node
I realize the title isn't too descriptive so here are the details. 我知道标题不太具描述性,因此以下是详细信息。 I'm implementing my own Binary Tree class in C++.
我正在用C ++实现自己的Binary Tree类。 I have written a template Node class and template Binary Tree class already, for the most part, and am stuck on something.
在大多数情况下,我已经编写了一个模板Node类和模板Binary Tree类,并且停留在某些东西上。 I created an empty binary tree (root node is null) and when I try to set that node it fails miserably.
我创建了一个空的二叉树(根节点为null),当我尝试设置该节点时,它会惨败。 here is the code and more explanation:
这是代码和更多说明:
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
};
Node implementation not really necessary.. ( I dont think ) it's quite long. 节点实现不是真正必要的..(我不认为)它很长。
#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;
}
}
Main: 主要:
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;
Inserts current functionality is just supposed to replace the NULL root pointer to the node pointer passed in as a parameter. 插入当前功能只是为了将NULL根指针替换为作为参数传入的节点指针。 The failing miserably part is since the pointer is a copy it isn't actually setting the root node.. but I can't seem to figure out how to set up a pointer to a pointer to the root node so it can be altered.. I've got to be close and any help will be MUCH appreciated.
可悲的失败部分是,由于指针是一个副本,它实际上并未设置根节点。.但是我似乎无法弄清楚如何设置指向根节点的指针,以便可以对其进行更改。我必须亲密接触,任何帮助将不胜感激。
Thanks 谢谢
First, you've got to include the exact text of any error messages. 首先,您必须包括所有错误消息的确切文本。 "fails miserably" is not adequate.
“惨败”是不够的。
I think you want 我想你要
root = node;
Not 不
*root = node;
Because if root is null, using *root is a null pointer exception. 因为如果root为null,则使用* root是null指针异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.