深入理解二叉搜索树:原理到实践

1.二叉搜索树的概念

⼆叉搜索树⼜称⼆叉排序树,它或者是⼀棵空树,或者是具有以下性质的⼆叉树

  • 若它的左树不为空,则左子树上所有节点的值都小于或等于根节点的值。
  • 若它的右树不为空,则右子树上所有节点的值都大于或等于根节点的值。
  • 它的左右子树也分别为二叉搜索树。
  • ⼆叉搜索树中可以⽀持插⼊相等的值,也可以不⽀持插⼊相等的值map/set/multimap/multiset系列容器底层就是⼆叉搜索树,其中map/set不⽀持插⼊相等 值,multimap/multiset⽀持插⼊相等值。

 

2.二叉搜索树的性能分析

最优情况下,二叉搜索树为完全⼆叉树(或者接近完全⼆叉树),其⾼度为:Olog2 N

 最差情况下,二叉搜索树退化为单⽀树(或者类似单⽀),其⾼度为:N 

所以综合⽽⾔二叉搜索树增删查改时间复杂度为:O(N)

⼆分查找也可以实现 O(logN) 2 级别的查找效率,但是⼆分查找有两⼤缺陷:

1. 需要存储在⽀持下标随机访问的结构中,并且有序。

2. 插⼊和删除数据效率很低,因为存储在下标随机访问的结构中,插⼊和删除数据⼀般需要挪动数 据。

3. 二叉搜索树的插⼊

插⼊的具体过程如下:

1. 树为空,则直接新增结点,赋值给root指针

2. 树不空,按⼆叉搜索树性质,插⼊值⽐当前结点⼤往右⾛,插⼊值⽐当前结点⼩往左⾛,找到空位 置,插⼊新结点。

3. 如果⽀持插⼊相等的值,插⼊值跟当前结点相等的值可以往右⾛,也可以往左⾛,找到空位置,插 ⼊新结点。(要注意的是要保持逻辑⼀致性,插⼊相等的值不要⼀会往右⾛,⼀会往左⾛)

 

 4. ⼆叉搜索树的查找

1.从根开始⽐较,查找x,x⽐根的值⼤则往右边⾛查找,x⽐根值⼩则往左边⾛查找。

2. 最多查找⾼度次,⾛到到空,还没找到,这个值不存在。

3. 如果不⽀持插⼊相等的值,找到x即可返回。

4. 如果⽀持插⼊相等的值,意味着有多个x存在,⼀般要求查找中序的第⼀个x。如下图,查找3,要 找到1的右孩⼦的那个3返回

5. ⼆叉搜索树的删除

⾸先查找元素是否在⼆叉搜索树中,如果不存在,则返回false。

如果查找元素存在则分以下四种情况分别处理:(假设要删除的结点为N)

1. 要删除结点N左右孩⼦均为空 2. 要删除的结点N左孩⼦位空,右孩⼦结点不为空

3. 要删除的结点N右孩⼦位空,左孩⼦结点不为空

 4. 要删除的结点N左右孩⼦结点均不为空

 对应以上四种情况的解决⽅案:

1. 把N结点的⽗亲对应孩⼦指针指向空,直接删除N结点(情况1可以当成2或者3处理,效果是⼀样 的)

2. 把N结点的⽗亲对应孩⼦指针指向N的右孩⼦,直接删除N结点

 3. 把N结点的⽗亲对应孩⼦指针指向N的左孩⼦,直接删除N结点

4. ⽆法直接删除N结点,因为N的两个孩⼦⽆处安放,只能⽤替换法删除。找N左⼦树的值最⼤结点 R(最右结点)或者N右⼦树的值最⼩结点R(最左结点)替代N,因为这两个结点中任意⼀个,放到N的 位置,都满⾜⼆叉搜索树的规则。替代N的意思就是N和R的两个结点的值交换,转⽽变成删除R结 点,R结点符合情况2或情况3,可以直接删除。

6. ⼆叉搜索树的实现代码

#include<iostream>
using namespace std;
template<class K>
struct BSTNode
{
	K _key;
	BSTNode<K>* _left;
	BSTNode<K>* _right;
	BSTNode(const K& key)
		:_key(key)
		, _left(nullptr)
		, _right(nullptr)
	{
	}
};
// Binary Search Tree
template<class K>
class BSTree
{
	typedef BSTNode<K> Node;
public:
	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key);
		if (parent->_key < key)
		{
			parent->_right = cur;
		}
		else
		{
			parent->_left = cur;
		}
		return true;
	}
	bool Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else
			{
				return true;
			}
		}
		return false;
	}
	bool Erase(const K& key)
	{
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				// 0-1个孩⼦的情况 
				// 删除情况1 2 3均可以直接删除,改变⽗亲对应孩⼦指针指向即可 
				if (cur->_left == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_right;
					}
					else
					{
						if (parent->_left == cur)
							parent->_left = cur->_right;
						else
							parent->_right = cur->_right;
					}
					delete cur;
					return true;
				}
				else if (cur->_right == nullptr)
				{
					if (parent == nullptr)
					{
						_root = cur->_left;
					}
					else
					{
						if (parent->_left == cur)
							parent->_left = cur->_left;
						else
							parent->_right = cur->_left;
					}
					delete cur;
					return true;
				}
				else
				{
					// 2个孩⼦的情况 
					// 删除情况4,替换法删除 
					// 假设这⾥我们取右⼦树的最⼩结点作为替代结点去删除 
					// 这⾥尤其要注意右⼦树的根就是最⼩情况的情况的处理,对应课件图中删除8的情况
						// ⼀定要把cur给rightMinP,否会报错。 
						Node* rightMinP = cur;
					Node* rightMin = cur->_right;
					while (rightMin->_left)
					{
						rightMinP = rightMin;
						rightMin = rightMin->_left;
					}
					cur->_key = rightMin->_key;
					if (rightMinP->_left == rightMin)
						rightMinP->_left = rightMin->_right;
					else
						rightMinP->_right = rightMin->_right;
					delete rightMin;
					return true;
				}
			}
		}
		return false;
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
private:
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
		
	}
private:
	Node* _root = nullptr;
};
int main() {
	BSTree<int> tree;

	// 插入操作
	tree.Insert(5);
	tree.Insert(3);
	tree.Insert(7);
	tree.Insert(2);
	tree.Insert(4);

	// 中序遍历(输出应为升序:2 3 4 5 7)
	tree.InOrder();

	// 查找操作
	cout << "Find 3: " << (tree.Find(3) ? "Yes" : "No") << endl;
	cout << "Find 6: " << (tree.Find(6) ? "Yes" : "No") << endl;

	// 删除操作
	tree.Erase(3);
	tree.InOrder(); // 输出应为:2 4 5 7

	return 0;
}

7. ⼆叉搜索树key和key/value使⽤场景

7.1 key搜索场景:

只有key作为关键码,结构中只需要存储key即可,关键码即为需要搜索到的值,搜索场景只需要判断 key在不在。key的搜索场景实现的⼆叉树搜索树⽀持增删查,但是不⽀持修改,修改key破坏搜索树结 构了。

场景1:⼩区⽆⼈值守⻋库,⼩区⻋库买了⻋位的业主⻋才能进⼩区,那么物业会把买了⻋位的业主的 ⻋牌号录⼊后台系统,⻋辆进⼊时扫描⻋牌在不在系统中,在则抬杆,不在则提⽰⾮本⼩区⻋辆,⽆法进⼊。 

7.2 key/value搜索场景:

每⼀个关键码key,都有与之对应的值value,value可以任意类型对象。树的结构中(结点)除了需要存 储key还要存储对应的value,增/删/查还是以key为关键字⾛⼆叉搜索树的规则进⾏⽐较,可以快速查找到key对应的value。key/value的搜索场景实现的⼆叉树搜索树⽀持修改,但是不⽀持修改key,修改key破坏搜索树性质了,可以修改value。

场景1:商场⽆⼈值守⻋库,⼊⼝进场时扫描⻋牌,记录⻋牌和⼊场时间,出⼝离场时,扫描⻋牌,查 找⼊场时间,⽤当前时间-⼊场时间计算出停⻋时⻓,计算出停⻋费⽤,缴费后抬杆,⻋辆离场。

#include <iostream>
#include <string>
using namespace std;

// 二叉搜索树节点定义(含键值对和父指针)
template <class K, class V>
struct BSTNode {
    K _key;                // 键
    V _value;              // 值
    BSTNode<K, V>* _left;  // 左子节点
    BSTNode<K, V>* _right; // 右子节点
    BSTNode<K, V>* _parent; // 父节点

    // 构造函数
    BSTNode(const K& key, const V& value, BSTNode* parent = nullptr)
        : _key(key), _value(value), _left(nullptr), _right(nullptr), _parent(parent) {}
};

// 二叉搜索树类模板
template <class K, class V>
class BSTree {
private:
    typedef BSTNode<K, V> Node; // 节点类型别名
    Node* _root;                // 根节点指针

    // 递归销毁树
    void _Destroy(Node* root) {
        if (root == nullptr) return;
        _Destroy(root->_left);
        _Destroy(root->_right);
        delete root;
    }

    // 递归拷贝树
    Node* _Copy(Node* root) {
        if (root == nullptr) return nullptr;
        Node* newNode = new Node(root->_key, root->_value);
        newNode->_left = _Copy(root->_left);
        newNode->_right = _Copy(root->_right);
        if (newNode->_left) newNode->_left->_parent = newNode;
        if (newNode->_right) newNode->_right->_parent = newNode;
        return newNode;
    }

    // 中序遍历辅助函数
    void _InOrder(Node* root) const {
        if (root == nullptr) return;
        _InOrder(root->_left);
        cout << root->_key << ": " << root->_value << endl;
        _InOrder(root->_right);
    }

public:
    // 默认构造函数
    BSTree() : _root(nullptr) {}

    // 拷贝构造函数
    BSTree(const BSTree& other) : _root(nullptr) {
        _root = _Copy(other._root);
    }

    // 赋值运算符
    BSTree& operator=(BSTree other) {
        swap(_root, other._root);
        return *this;
    }

    // 析构函数
    ~BSTree() {
        _Destroy(_root);
        _root = nullptr;
    }

    // 插入键值对(不允许重复键)
    bool Insert(const K& key, const V& value) {
        Node* newNode = new Node(key, value);
        if (_root == nullptr) {
            _root = newNode;
            return true;
        }

        Node* parent = nullptr;
        Node* cur = _root;
        while (cur) {
            if (cur->_key < key) {
                parent = cur;
                cur = cur->_right;
            } else if (cur->_key > key) {
                parent = cur;
                cur = cur->_left;
            } else {
                delete newNode; // 重复键,释放内存
                return false;
            }
        }

        newNode->_parent = parent;
        if (parent->_key < key) {
            parent->_right = newNode;
        } else {
            parent->_left = newNode;
        }
        return true;
    }

    // 查找键对应的节点(返回值指针,失败返回nullptr)
    V* Find(const K& key) {
        Node* cur = _root;
        while (cur) {
            if (cur->_key < key) {
                cur = cur->_right;
            } else if (cur->_key > key) {
                cur = cur->_left;
            } else {
                return &cur->_value; // 返回值的指针
            }
        }
        return nullptr;
    }

    // 查找键对应的节点(const版本)
    const V* Find(const K& key) const {
        Node* cur = _root;
        while (cur) {
            if (cur->_key < key) {
                cur = cur->_right;
            } else if (cur->_key > key) {
                cur = cur->_left;
            } else {
                return &cur->_value;
            }
        }
        return nullptr;
    }

    // 删除指定键的节点
    bool Erase(const K& key) {
        Node* cur = _root;
        Node* parent = nullptr;

        // 查找节点
        while (cur && cur->_key != key) {
            parent = cur;
            if (cur->_key < key) {
                cur = cur->_right;
            } else {
                cur = cur->_left;
            }
        }
        if (cur == nullptr) return false; // 未找到

        // 删除节点处理
        if (cur->_left == nullptr) { // 左子树为空
            Node* child = cur->_right;
            if (parent == nullptr) { // 删除根节点
                _root = child;
            } else {
                if (parent->_left == cur) {
                    parent->_left = child;
                } else {
                    parent->_right = child;
                }
            }
            if (child) child->_parent = parent;
            delete cur;
        } else if (cur->_right == nullptr) { // 右子树为空
            Node* child = cur->_left;
            if (parent == nullptr) {
                _root = child;
            } else {
                if (parent->_left == cur) {
                    parent->_left = child;
                } else {
                    parent->_right = child;
                }
            }
            if (child) child->_parent = parent;
            delete cur;
        } else { // 左右子树都存在,找右子树最小节点替换
            Node* rightMin = cur->_right;
            Node* rightMinParent = cur;
            while (rightMin->_left) {
                rightMinParent = rightMin;
                rightMin = rightMin->_left;
            }

            // 替换值
            cur->_key = rightMin->_key;
            cur->_value = rightMin->_value;

            // 删除右子树最小节点
            if (rightMinParent == cur) {
                rightMinParent->_right = rightMin->_right;
            } else {
                rightMinParent->_left = rightMin->_right;
            }
            if (rightMin->_right) {
                rightMin->_right->_parent = rightMinParent;
            }
            delete rightMin;
        }
        return true;
    }

    // 中序遍历(升序输出键值对)
    void InOrder() const {
        _InOrder(_root);
        cout << endl;
    }
};

// 测试用例
int main() {
    // 测试1:单词词典
    BSTree<string, string> dict;
    dict.Insert("apple", "苹果");
    dict.Insert("banana", "香蕉");
    dict.Insert("grape", "葡萄");
    dict.Insert("mango", "芒果");

    cout << "单词词典中序遍历:" << endl;
    dict.InOrder();

    // 查找单词
    string word = "banana";
    auto value = dict.Find(word);
    if (value) {
        cout << "单词 " << word << " 的翻译是:" << *value << endl;
    } else {
        cout << "未找到单词 " << word << endl;
    }

    // 删除单词
    dict.Erase("grape");
    cout << "删除grape后的词典:" << endl;
    dict.InOrder();

    // 测试2:水果计数
    string fruits[] = {"苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉"};
    BSTree<string, int> fruitCount;
    for (const auto& fruit : fruits) {
        auto cnt = fruitCount.Find(fruit);
        if (cnt) {
            (*cnt)++; // 计数加一
        } else {
            fruitCount.Insert(fruit, 1); // 首次插入
        }
    }

    cout << "水果计数结果:" << endl;
    fruitCount.InOrder();

    // 测试拷贝构造和赋值运算符
    BSTree<string, int> copyTree = fruitCount;
    cout << "拷贝构造后的计数:" << endl;
    copyTree.InOrder();

    BSTree<string, int> assignTree;
    assignTree = copyTree;
    cout << "赋值后的计数:" << endl;
    assignTree.InOrder();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值