构造一个二叉搜索树,查找指定元素的值,代码案例如下:
#include <iostream>
using namespace std;
struct TreeNode {
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int value):data(value), left(nullptr), right(nullptr){}
};
//向二叉搜索树插入节点
void insert(TreeNode *&root, int value)
{
if (root == nullptr)
{
root = new TreeNode(value);
}
else if (value < root->data)
{
insert(root->left, value);
}
else
{
insert(root->right, value);
}
}
//向二叉搜索树查找节点
TreeNode *search(TreeNode *root, int value)
{
if (root == nullptr || root ->data == value)
{
return root;
}
if (value < root->data)
{
return search(root->left, value);
}
return search(root->right, value);
}
//中序遍历二叉搜索树
void midTreefun(TreeNode *root)
{
if (root == nullptr)
{
return;
}
midTreefun(root->left);
cout << "root->data = " << root->data << ",";
midTreefun(root->right);
}
int main()
{
TreeNode *root = nullptr;
insert(root, 2);
insert(root, 3);
insert(root, 4);
insert(root, 5);
insert(root, 6);
insert(root, 7);
insert(root, 8);
insert(root, 9);
cout << "begin mid tree" << endl;
midTreefun(root);
cout << endl;
int value = 6;
TreeNode *node = search(root, value);
if (node != nullptr)
{
cout << "value = " << value << endl;
}
else
{
cout << "没找到该value值" << endl;
}
return 0;
}
//输出:
begin mid tree
root->data = 2,root->data = 3,root->data = 4,root->data = 5,root->data = 6,root->data = 7,root->data = 8,root->data = 9,
value = 6