二叉查找树,是一种基于节点的二叉树,有下面的性质:
二叉查找树的上述性质,保证了各节点值的顺序,这样进行查找,求最大值最小值时,会效率更高。如果没有这种顺序,则可能需要将树中的每个节点与指定的查找值进行比较。
//在二叉搜索树中查找特定的值
Node* search(Node* root, int key)
{
// Base Cases: 空树或者值为根节点值
if (root == NULL || root->key == key)
return root;
// 指定值大于根值
if (root->key < key)
return search(root->right, key);
// 指定值小于根植
return search(root->left, key);
}
100 100
/ \ Insert 40 / 20 500 ---------------------> 20 500
/ \ / \
10 30 10 30
\
40
#include <iostream>
struct Node
{
int key;
Node *left;
Node *right;
};
// 创建一个新的BST节点
Node *createNewNode(int item)
{
Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// 中序遍历二叉搜索树
void inorder(Node *root)
{
if (root != NULL)
{
inorder(root->left);
std::cout<<" "<<root->key<<" ";
inorder(root->right);
}
}
//插入新节点至二叉搜索树中
Node* insert(Node* node, int key)
{
//空树
if (node == NULL)
return createNewNode(key);
//递归插入。如果已存在指定值,则不插入
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
//返回未修改的node指针
return node;
}
int main()
{
/* 构建一颗如下所示的BST
50
/ 30 70
/ \ / 20 40 60 80
*/
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// 中序遍历
inorder(root);
return 0;
}输出:
20 30 40 50 60 70 80
时间复杂度: 最差的查找以及插入操作的时间复杂度为O(h),其中h是树的高度。在最差情况下,可能需要从根节点一直遍历到叶子节点。原文:http://blog.csdn.net/shltsh/article/details/46509323