这是我的代码:
template <typename DataType> bool SearchValue(TreeNode<DataType> *root, DataType search_value)
{
if(search_value != root->data)
{
if(root->right != NULL)
{
return SearchValue(root->right, search_value);
}
if (root->left != NULL)
{
return SearchValue(root->left, search_value);
}
return false;
}
else
{
return true;
}
}
我无法使SearchValue
功能正常工作。条件是不改变SearchValue
函数的签名。问题如下:例如,我们尝试查找数据字段等于“90”的元素并且它存在于树中。有时这段代码会找到这个元素,有时却找不到——这取决于它在树中的位置。问题是如何让它每次都能正常工作。
我以这种方式构建树:
template <typename DataType> TreeNode<DataType> *BuildTree()
{
TreeNode<DataType> *root = new TreeNode<DataType>(10, new TreeNode<DataType>(20), new TreeNode<DataType>(30));
TreeNode<DataType> *curRoot = root;
curRoot = curRoot->left;
curRoot->left = new TreeNode<DataType>(40);
curRoot->left->left = new TreeNode<DataType>(70);
curRoot->right = new TreeNode<DataType>(50);
curRoot = curRoot->right;
curRoot->left = new TreeNode<DataType>(80, new TreeNode<DataType>(100), new TreeNode<DataType>(110));
curRoot = root->right;
curRoot->left = new TreeNode<DataType>(60);
curRoot = curRoot->left;
curRoot->right = new TreeNode<DataType>(90, new TreeNode<DataType>(120), new TreeNode<DataType>(130));
return root;
}
我以这种方式测试搜索:
TreeNode<int> *treeRoot = BuildTree<int>();
int valueToFind = treeRoot->data;
cout << "Enter the value you'd like to find in the tree: ";
cin >> valueToFind;
cin.get();
if(SearchValue(treeRoot, valueToFind) == true)
{
cout << "Value " << valueToFind << " was found!";
}
我实现树的方式:
template <typename DataType> struct TreeNode
{
TreeNode(DataType val, TreeNode<DataType> *leftPtr = NULL, TreeNode<DataType> *rightPtr = NULL)
{
left = leftPtr;
right = rightPtr;
data = val;
}
TreeNode<DataType> *left, *right;
DataType data;
};