【发布时间】:2015-03-28 09:07:23
【问题描述】:
我正在使用 VS13 为学校开发 C++ 程序。我需要将数据插入 BST。我得到了一个定义为 Add(int dataValue); 的函数。 (在 public 下)只取数据值。我定义了第二个 Add() 函数,它也将 Node* 作为参数,以便使 Add() 递归。 (参见下面的 .h 部分代码)
#include <iostream>
#include <queue>
class HW2BST
{
private:
struct Node
{
int Data;
Node* Left;
Node* Right;
Node(int dataValue);
};
Node* m_root;
bool Add(Node* root, int dataValue);
public:
bool Add(int dataValue);
我的问题是,当从 main 调用 tree.Add(int) 时,我尝试将 m_root 传递给第二个 Add(Node*, int) 函数以插入数据。单步执行该函数并观察 m_root 和 root 运行时,我看到 Add(Node*, int) root 内部设置为 NULL,如我所料。当它逐步通过 root->Data 时,dataValue 被正确分配,并且 root->Left 和 root->Right 被正确分配为 NULL。但是这些分配不会传回给 m_root。一旦函数退出,root 就会被销毁,m_root 不会更新,我就没有树了。 (参见下面的 .cpp)
#include "HW2BST.h"
using namespace std;
HW2BST::Node::Node(int dataValue)
{
Data = dataValue;
Left = Right = NULL;
}
HW2BST::HW2BST(void)
{
m_root = NULL;
}
bool HW2BST::Add(int dataValue)
{
return Add(m_root, dataValue); // Add (overload) recursively searches then inserts dataValue, then returns result
}
bool HW2BST::Add(Node* root, int dataValue)
{
if (!root) // verify if node exists
{
root = new Node(dataValue); // if node does not exist, implement new node and set dataValue
if (!root) // if node not allocated correctly, return false
return false;
else // else return true (both new node implemented and value added to tree)
return true;
}
else if (dataValue < root->Data) // if not empty, check data value with current data
return Add(root->Left, dataValue); // if less than, travel down left child
else if (dataValue > root->Data)
return Add(root->Right, dataValue); // if greater than, travel down right child
else
return false; // if equal to, ignore (double entry)
}
我已经和我的教授谈过了,他说了一些关于使用 Node** 的事情,但是当我尝试时我无法让类型协调(即 root->Data 不断抛出错误 C2227)。
我知道解决方案很简单,但我似乎无法理解我所缺少的。
【问题讨论】: