思想
比较要查找的元素和当前节点的大小,如果比当前节点大,则去当前节点的右子树查找,否则去左子树查找
例如:42先和41比,比41大,所以在41的右子树中继续查找42
42比58小,在58的左子树继续查找
42比50小,在50的左子树继续查找
查找失败:元素不存在
59比41大,在41的右子树继续查找
59比58大,在58的右子树继续查找
59比60小,在60的左子树继续查找,60的左子树为空,查找失败
实现
Contain:查找key的值是否存在于二叉树中
Search:查找key对应----可以是对应的Node/value
#include <iostream>
using namespace std;
template <typename Key,typename Value>
//定义一棵二分搜索树
class BST{
private:
//树的一个节点定义
struct Node{
Key key;
Value value;
Node* left;//左孩子
Node* right;//右孩子
Node(Key key, Value value) //构造函数
{
this->key=key;
this->value=value;
this->right=this->left=NULL;
}
Node(Node* node) //构造函数
{
this->key=node->key;
this->value=node->value;
this->right=node->right;
this->left=node->left;
}
};
Node* root;//树的根节点
int count;//树的节点数
public:
BST()
{
count=0;
root=NULL;
}
int size()
{
return count;
}
bool isEmpty()
{
return count==0;
}
//查找树中是否有key值的节点
bool contain(Key key)
{
return contain(root,key);
}
//查找树中key对应的value ,由于可能为NULL,所以返回指针
Value* search(Key key)
{
return search(root,key);
}
private:
//在以node为根节点的树中查找key值是否存在
bool contain(Node* node,Key key)
{
if(node == NULL)
return false;
if(node->key==key)
return true;
else if(key<node->key) //key值可能存在node的左子树
return contain(node->left,key);
else
return contain(node->right,key);
}
//在以node为根节点的树中查找key值对应的value
Value* search(Node* node,Key key)
{
if(node==NULL)
return NULL;
if(node->key==key)
return &(node->value);
else if(key<node->key) //key值可能存在node的左子树
return search(node->left,key);
else
return search(node->right,key);
}
};