二叉搜索树的C++代码实现

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值