template<class K,class V>
struct BinaryNode{
K _key;
V _value;
BinaryNode<K,V>* _left;
BinaryNode<K,V>* _right;
BinaryNode(const K& key,const V& value)
:_key(key), _value(value), _left(NULL), _right(NULL)
{}
};
/*****************二叉搜索树*******************************
1.每个节点都有一个作为搜索依据的键值K,每个节点的K互不相同。
2.左子树上的所有节点的K都小于根节点的K。
3.右子树上的所有节点的K都大于根节点的K。
4.左右子树也都是二叉搜索树。
***********************************************************/
template<class K,class V>
class SearchTree{
typedef BinaryNode<K,V> Node;
public:
SearchTree()
:_root(NULL)
{}
void Insert(const K& key,const V& value)
{
//树为空时
if (_root == NULL)
_root = new Node(key,value);
Node* cur = _root;
Node* parent = NULL;//记录上一个节点,因为当cur走到地方,要根据与上一节点比较的大小,来决定插入左还是右
while (cur){
if (key < cur->_key){
parent = cur;
cur = cur->_left;
}
else if (key > cur->_key){
parent = cur;
cur = cur->_right;
}
else{//因为每个节点的K不能相同,所以无法插入
return;
}
}
//已经找到了位置,插入
cur = new Node(key,value);
if (key < parent->_key)
parent->_left = cur;
if (key > parent->_key)
parent->_right = cur;
return;
}
Node* Find(const K& key)//O(lgN)
{
Node* cur = _root;
while (cur){
if (key < cur->_key)
cur = cur->_left;
else if (key > cur->_key)
cur = cur->_right;
else
return cur;
}
return NULL;
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
private:
void _InOrder(Node* _root)
{
if (_root == NULL)
return;
_InOrder(_root->_left);
cout << _root->_key << " ";
_InOrder(_root->_right);
}
private:
Node* _root;
};
//*************二叉搜索树变双链表***************
struct TreeNode{
int _key;
TreeNode* _left;
TreeNode* _right;
TreeNode(int key)
:_key(key)
, _left(NULL)
, _right(NULL)
{}
};
void Func(TreeNode* node, TreeNode** tail)
{
if (node == NULL)
return;
Func(node->_left, tail);//中序,先走到最左节点
//把最左节点和tail连接
node->_left = (*tail);
if ((*tail) != NULL)
(*tail)->_right = node;
//每一层给tail赋值
(*tail) = node;
//如果node有右子树,就走到右边
if (node->_right)
Func(node->_right, tail);
}
TreeNode* TreeToList(TreeNode* root)
{
TreeNode* tail = NULL;
Func(root, &tail);
//双链表,知道了尾节点,走到头,返回
TreeNode* head = tail;
while (head && head->_left){
head = head->_left;
}
return head;
}