将节点添加到二叉搜索树c ++

时间:2013-07-09 18:25:02

标签: c++ binary-search-tree

我正在构建一个二叉搜索树。现在我遇到了向树添加节点的问题。

void BinaryTree::add(int value, Node* node) {
    if(!node)
        node = new Node(value);
    else if(node->key < value)
        this->add(value, node->rightNode);
    else if(node->key > value)
        this->add(value, node->leftNode);
}

当我打电话时,这段代码似乎不起作用:

BinaryTree test;
test.add(4, test.root);
test.add(1, test.root);
test.add(5, test.root);
test.add(2, test.root);
test.add(3, test.root);
test.add(7, test.root);
test.add(6, test.root);

在第一次添加调用之后,树'test'的根仍然是空的。 我如何更改代码,以便在调用add并且节点到达树的正确位置时更新代码? 非常感谢你!

2 个答案:

答案 0 :(得分:1)

您在此处传递Node *值:

void BinaryTree::add(int value, Node* node) {

一种解决方案是通过引用传递:

void BinaryTree::add(int value, Node *& node) {
                                      ^

如果你通过值传递,该函数只是接收Node *的副本,因此对它的任何修改都不会反映在调用代码中。

另外,您可能想要考虑当value等于key时会发生什么。

答案 1 :(得分:0)

您递归调用add函数,但在那里我没有看到您实际上将leftNode或rightNode分配给传入的节点。