问题
I am trying to make a binary search tree using C++. I am using only the functions to insert data and find data. I can't seem to get the program to work, although I find that it is very logic and correct?
Any help would be greatly appreciated.
#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);
}
回答1:
One problem is here.
if(current->data > toFindNum)
current = current->rightchild;
Consider this tree.
5
/ \
4 6
Your toFindNum
is 4. If current->data
is 5, greater than 4, you need to look in the left child, not right one.
Your statement should be this.
if(current->data > toFindNum)
current = current->leftchild;
else
current = current->rightchild;
回答2:
In searchForItem
if(current->data > toFindNum)
shouldn't that be:
if (toFindNum > current->data)
来源:https://stackoverflow.com/questions/14111373/binary-search-tree