-4

我正在尝试使用 C++ 创建二叉搜索树。我只使用插入数据和查找数据的函数。我似乎无法让程序运行,尽管我发现它非常合乎逻辑且正确?

任何帮助将不胜感激。

#include<iostream>
using namespace std;

template <class T>
class BinarySearchTree
{
private:
    struct tree
    {
        tree *leftchild;
        tree *rightchild;
        T data;
    };
    tree *root;
public:
    BinarySearchTree()
    {
        root=NULL; 
    }
    void insert(T);
    void searchForItem(T);
};

template<class T>
void BinarySearchTree<T>::insert(T newNum)
{
    tree *newItem = new tree; 
    tree *parent; 

    newItem->data = newNum;
    newItem->leftchild = NULL;
    newItem->rightchild = NULL;

    if(root==NULL) 
        root=newItem;

    else
    {
        tree *current;
        current=root;
        while(current) 
        {
            parent = current;

            if(newItem->data > current->data)
                current = current->rightchild;
            else
                current = current->leftchild;
        }

        if(newItem->data > parent->data)
            parent->rightchild = newItem;
        else
            parent->leftchild = newItem;
    }

}

template<class T>
void BinarySearchTree<T>::searchForItem(T toFindNum)
{
    tree *current;
    tree *parent;

    current = root;
    if(current->data == toFindNum)
        cout<<toFindNum<<" is the root of this binary search tree."<<endl;

    while(current->data != toFindNum)
    {
        parent = current;

        if(current->data > toFindNum)
            current = current->rightchild;
        else
            current = current->leftchild;
    }

    cout<<toFindNum<<" is the child of "<<parent->data<<endl;
}
int main()
{
    BinarySearchTree<int> b;

    b.insert(5);
    b.insert(4);
    b.insert(3);
    b.insert(2);
    b.insert(7);

    b.searchForItem(4);
} 
4

2 回答 2

6

这里有一个问题。

if(current->data > toFindNum)
    current = current->rightchild;

考虑这棵树。

  5
 /  \
 4   6

toFindNum是 4。如果current->data是 5,大于 4,你需要看左孩子,而不是右孩子。

你的陈述应该是这样的。

if(current->data > toFindNum)
    current = current->leftchild;
else
current = current->rightchild;
于 2013-01-01T14:54:08.463 回答
0

searchForItem

if(current->data > toFindNum)

那不应该是:

if (toFindNum > current->data)
于 2013-01-01T14:53:16.853 回答