1

这个问题与二叉搜索树有关。这是我正在使用的节点的定义

struct _Node
{
    _Node *Parent;
    int Data;
    _Node *Left;
    _Node *Right;
};

现在这里是创建根后添加节点的函数的定义

void AddNode(_Node *Incoming, _Node *currentNode)
{

            if(!currentNode)
            {
                currentNode = Incoming;
            }
            else if(currentNode->Data >= Incoming->Data)
            {
                Incoming->Parent = currentNode;
                AddNode(Incoming, currentNode->Left);
            }
            else if(currentNode->Data < Incoming->Data)
            {
                Incoming->Parent = currentNode;
                AddNode(Incoming, currentNode->Right);
            }

}

AddNode 函数基于递归方法。主要代码是

_Node *Root= new _Node;
Root->Data = 50;
Root->Parent = nullptr;
Root->Left = nullptr;
Root->Right = nullptr;


_Node *Node2 = new _Node;
Node2->Data = 25;
Node2->Parent = nullptr;
Node2->Left = nullptr;
Node2->Right = nullptr;
_Node *Node3 = new _Node;

   AddNode(Node2, Root);

问题:一旦我退出添加节点功能,我发现 Root 节点没有设置为 Node2 的 Left 或 Right Child。据我说,每次我应该将节点正确添加到根时,都会传递指向节点的指针。这没有发生。你能帮我看看我犯了什么错误吗?

4

1 回答 1

0

尝试

AddNode(Incoming, currentNode->Left);

代替

AddNode(Incoming, Incoming->Left);

Right.

于 2012-08-12T19:03:20.550 回答