因此,对于我的任务,我应该实现一个Node类,该类仅包含指向其两个兄弟的数据和指针,以及读取这些节点并从中创建二进制树的BinaryTree。我的问题是指向树的根似乎没有工作。任何帮助,您可以提供将不胜感激!标识符未找到
注意:错误发现在BinaryTree.cpp文件的addNode方法中可以找到,它可以在问题的最后找到。另外,我也无法访问大小的值,所以我认为这是我无法解决的一些奇怪的范围问题。我也不能在addNode函数中使用“this”关键字。
根据我的作业指导,我也不允许使用结构。
Node.H
#include <iomanip>
using namespace std;
class Node
{
public:
int data;
Node* leftChild;
Node* rightChild;
Node(int data, Node* leftChild, Node* rightChild);
};
Node.cpp
#include <iomanip>
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(int data, Node* leftChild, Node* rightChild)
{
this->data = data;
this->leftChild = leftChild;
this->rightChild = rightChild;
}
BinaryTree.H
#include <iomanip>
#include "Node.h"
using namespace std;
class Tree
{
public:
Tree(int data);
void addNode(int data);
void inOrder(Node* N);
protected:
Node* root;
int size;
int data;
private:
int printNode(Node* N);
};
BinaryTree.cpp
#include <iostream>
#include <iomanip>
#include "BinaryTree.h"
using namespace std;
//Tree constructor. Sets the values of data, size, and root.
Tree::Tree(int data)
{
this->data = data;
this->size = 0;
this->root = new Node(data, NULL, NULL);
}
//Adds a node to the current Tree.
void addNode(int data)
{
Node* tempNode = new Node(data, NULL, NULL);
Node* current = root; //THIS IS THE ERROR LINE.
while(current!=NULL)
{
//If the data we are trying to add is already in the Tree
if(current->data == tempNode->data)
{
cout << "Data already in the Tree.";
}
//If the data for the new node is larger than the old
else if(current->data < tempNode->data)
{
//See if the right child is null. If so, add the tree node there.
if(current->rightChild == NULL)
{
current->rightChild = tempNode;
return;
}
//Otherwise, traverse down the right tree.
else
{
current = current->rightChild;
}
}
//The data is smaller than the current node
else
{
//See if the left child is null. If so, add the tree node there.
if(current->leftChild == NULL)
{
current->leftChild = tempNode;
return;
}
//Otherwise, traverse down the left tree
else
{
current = current->leftChild;
}
}//End of leftChild Else
}//End of while
}//End of addNode
什么是 “当前的树”? –
这是不相关的,因此我发布这个评论而不是答案的原因;但是根据您在此发布的代码,您不需要在.h文件中包含“”标头,因为它们将它们包含在.cpp文件中。避免在头文件中包含文件通常是一个好主意,因为这会迫使任何使用你的类的人包含这些文件。 –
@DavidSchwartz,currentTree应该是addNode方法试图添加新节点的当前节点。对不起,我没有说清楚。 – jtrevag