Ser*_*iev 0 c++ recursion binary-tree
这是我的代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我无法使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;
}
Run Code Online (Sandbox Code Playgroud)
我用这种方式测试搜索:
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!";
}
Run Code Online (Sandbox Code Playgroud)
我实现树的方式:
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;
};
Run Code Online (Sandbox Code Playgroud)