二叉搜索树——BinarySearchTree

致前行的人:

                要努力,但不要着急,繁花锦簇,硕果累累,都需要过程!

目录

1.二叉搜索树

1.1二叉搜索树概念

 1.2二叉搜索树的操作

1.3二叉搜索树的实现

2.4二叉搜索树的应用

2.5二叉搜索树的性能分析

2.二叉树的面试题


1.二叉搜索树

1.1二叉搜索树概念

二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
        若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
        若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
        它的左右子树也分别为二叉搜索树

如下图所示:

 1.2二叉搜索树的操作

int a[] = {8, 3, 1, 10, 6, 4, 7, 14, 13};

1. 二叉搜索树的查找
a、从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。
b、最多查找高度次,走到到空,还没找到,这个值不存在。

2. 二叉搜索树的插入
插入的具体过程如下:
a. 树为空,则直接新增节点,赋值给root指针
b. 树不空,按二叉搜索树性质查找插入位置,插入新节点


1. 二叉搜索树的删除
首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情
况:
a. 要删除的结点无孩子结点
b. 要删除的结点只有左孩子结点
c. 要删除的结点只有右孩子结点
d. 要删除的结点有左、右孩子结点
看起来有待删除节点有4中情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程
如下:
情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点--直接删除
情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点--直接删除
情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题--替换法删除

 

1.3二叉搜索树的实现

template <class K>
struct BinarySearchTreeNode
{
	K _key;
	BinarySearchTreeNode<K>* _left;
	BinarySearchTreeNode<K>* _right;
	BinarySearchTreeNode(const K& val) :_key(val), _left(nullptr), _right(nullptr) {}
};
template <class K>
class BinarySearchTree
{
	typedef BinarySearchTreeNode<K> Node;
public:
	BinarySearchTree() : _root(nullptr) {}
	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		Node* prev = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				prev = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				prev = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key);
		if (prev->_key < key)
		{
			prev->_right = cur;
		}
		else
		{
			prev->_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* prev = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				prev = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				prev = cur;
				cur = cur->_left;
			}
			else
			{
				//左为空
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_right;
					}
					else
					{
						if (prev->_left == cur)
						{
							prev->_left = cur->_right;
						}
						else
						{
							prev->_right = cur->_right;
						}
					}					
					delete cur;
				}
				//右为空
				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
					}
					else
					{
						if (prev->_right == cur)
						{
							prev->_right = cur->_left;
						}
						else
						{
							prev->_left = cur->_left;
						}
					}
					delete cur;
				}
				//两者都不为空:找右子树最小结点
				else
				{
					Node* prev = cur;
					Node* minRight = cur->_right;
					while (minRight->_left)
					{
						prev = minRight;
						minRight = minRight->_left;
					}
					cur->_key = minRight->_key;
					if (prev->_left == minRight)
					{
						prev->_left = minRight->_right;
					}
					else
					{
						prev->_right = minRight->_right;
					}
					delete minRight;
				}
				return true;
			}
		}
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
	//递归查找,插入,删除:
	bool FindR(const K& key)
	{
		return _FindR(_root, key);
	}
	bool InsertR(const K& key)
	{
		return _Insert(_root, key);
	}
	bool EraseR(const K& key)
	{
		return _Erase(_root, key);
	}
private:
	bool _Erase(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			return false;
		}
		if (root->_key < key)
		{
			_Erase(root->_right, key);
		}
		else if (root->_key > key)
		{
			_Erase(root->_left, key);
		}
		else
		{
			Node* del = root;
			if (root->_left == nullptr)
			{
				root = root->_right;
			}
			else if(root->_right == nullptr)
			{
				root = root->_left;
			}
			else
			{
				Node* minRight = root->_right;
				while (minRight->_left)
				{
					minRight = minRight->_left;
				}
				swap(root->_key, minRight->_key);
				_Erase(root->_right, key);
			}
			delete del;
			return true;
		}
	}
	bool _Insert(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			root = new Node(key);
			return true;
		}
		if (root->_key < key)
		{
			_Insert(root->_right, key);
		}
		else if (_root->_key > key)
		{
			_Insert(root->_left, key);
		}
		else
		{
			return false;
		}
	}
	bool _FindR(Node* root, const K& key)
	{
		if (root == nullptr)
			return false;
		if (root->_key < key)
		{
			_FindR(root->_right, key);
		}
		else if (root->_key > key)
		{
			_FindR(root->_left, key);
		}
		else
		{
			return true;
		}
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;
		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
	}
private:
	Node* _root;
};

2.4二叉搜索树的应用

template <class K,class V>
struct BinarySearchTreeNode
{
	K _key;
	V _value;
	BinarySearchTreeNode<K,V>* _left;
	BinarySearchTreeNode<K,V>* _right;
	BinarySearchTreeNode(const K& key = K(),const V& val = V())
		:_key(key),_value(val) ,_left(nullptr), _right(nullptr) {}
};
template <class K,class V>
class BinarySearchTree
{
	typedef BinarySearchTreeNode<K,V> Node;
public:
	BinarySearchTree() : _root(nullptr) {}
	bool Insert(const K& key,const V& val)
	{
		if (_root == nullptr)
		{
			_root = new Node(key,val);
			return true;
		}
		Node* prev = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				prev = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				prev = cur;
				cur = cur->_left;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key,val);
		if (prev->_key < key)
		{
			prev->_right = cur;
		}
		else
		{
			prev->_left = cur;
		}
		return true;
	}
	Node* 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;
			}
		}
		return nullptr;
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
private:
	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;
		_InOrder(root->_left);
		cout << root->_key << ":" << root->_value << endl;
		_InOrder(root->_right);
	}
private:
	Node* _root;
};

1. K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值。
                比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:
                以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树
                在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。

void Test1()
{
	// 输入单词,查找单词对应的中文翻译
	BinarySearchTree<string, string> dict;
	dict.Insert("string", "字符串");
	dict.Insert("tree", "树");
	dict.Insert("left", "左边");
	dict.Insert("right", "右边");
	dict.Insert("sort", "排序");
	string str;
	while (cin >> str)
	{
		BinarySearchTreeNode<string, string>* ret = dict.Find(str);
		if (ret)
		{
			cout << "中文翻译:" << ret->_value << endl;
		}
		else
		{
			cout << "无此单词" << endl;
		}
	}
}


2. KV模型:每一个关键码key,都有与之对应的值Value,即<Key, Value>的键值对。该种方式在现实生活中非常常见:
        比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文<word, chinese>就构成一种键值对;
        再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是<word, count>就构成一种键值对。

void Test2()
{
	// 统计水果出现的次数
	string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
	"苹果", "香蕉", "苹果", "香蕉" };
	BinarySearchTree<string, int> countTree;
	for (const auto& str : arr)
	{
		// 先查找水果在不在搜索树中
		// 1、不在,说明水果第一次出现,则插入<水果, 1>
		// 2、在,则查找到的节点中水果对应的次数++
		//BinarySearchTreeNode<string, int>* ret = countTree.Find(str);
		auto ret = countTree.Find(str);
		if (ret == NULL)
		{
			countTree.Insert(str, 1);
		}
		else
		{
			ret->_value++;
		}
	}
	countTree.InOrder();
}

2.5二叉搜索树的性能分析

对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度的函数,即结点越深,则查找次数越多。

但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:

最优情况下,二叉搜索树为完全二叉树(或者接近完全二叉树),其平均比较次数为:logN 

最差情况下,二叉搜索树退化为单支树(或者类似单支),其平均比较次数为:O(N)

2.二叉树的面试题

1. 二叉树创建字符串。oj链接

实现思路:采用前序遍历的方式,不同的是当左子树为空而右子树不为空时,需要将空结点用“()”标识出来

class Solution {
public:
    string tree2str(TreeNode* root) 
    {
        if(root == nullptr)
            return string();
        string str; 
        str += to_string(root->val);
        if(root->left)
        {
            str += '(';
            str += tree2str(root->left);
            str += ')';
        }
        else if(root->right)//左为空,右不为空
        {
            str += "()";
        }
        if(root->right)
        {
            str += '(';
            str += tree2str(root->right);
            str += ')';
        }
        return str;
    }
};


2. 二叉树的分层遍历1oj链接

实现思路:借助队列,采用层序遍历的方式:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if(root == nullptr)
            return result;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            vector<int> v;
            for(int i = 0; i < size; i++)
            {
                TreeNode* front = q.front();
                q.pop();
                v.push_back(front->val);
                if(front->left)
                {
                    q.push(front->left);
                }
                if(front->right)
                {
                    q.push(front->right);
                }
            }
            result.push_back(v);
        }
        return result;
    }
};


3. 二叉树的分层遍历2。oj链接

实现思路:借助队列,采用层序遍历的方式,最后将结果逆置一下

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>>result;
        if (root == nullptr)
            return result;
        queue<TreeNode*>q;
        q.push(root);
        while (!q.empty())
        {
            vector<int>v;
            int size = q.size();
            for (size_t i = 0; i < size; ++i)
            {
                TreeNode* front = q.front();
                q.pop();
                v.push_back(front->val);
                if (front->left)
                    q.push(front->left);
                if (front->right)
                    q.push(front->right);
            }
            result.push_back(v);
        }
        reverse(result.begin(), result.end());
        return result;
    }

};


4. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 oj链接

思路1:暴力查找,分为三种情况:1.p和q都在左子树  2.p和q都在右子树  3.p在左子树,q在右子树/p在右子树,q在左子树

class Solution {
public:
    bool FindNode(TreeNode* root, TreeNode* node)
    {
        if (root == nullptr)
            return false;
        if (root == node)
            return true;
        return FindNode(root->left, node) ||
            FindNode(root->right, node);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if (root == nullptr)
            return nullptr;
        if (root == q || root == p)
            return root;
        //1.p和q都在左子树  2.p和q都在右子树  3.p在左子树,q在右子树/p在右子树,q在左子树
        bool pInLeft = FindNode(root->left, p);
        bool pInRight = !pInLeft;
        bool qInLeft = FindNode(root->left, q);
        bool qInRight = !qInLeft;
        if (pInLeft && qInRight || pInRight && qInLeft)
            return root;
        if (pInLeft && qInLeft)
            return lowestCommonAncestor(root->left, p, q);
        else
            return lowestCommonAncestor(root->right, p, q);
    }
};

思路2:借助vector,将p和q结点的路径保存起来,然后转化为求链表相加的思路求取公共祖先

class Solution {
public:
    bool GetPath(TreeNode* root, TreeNode* node, vector<TreeNode*>& path)
    {
        if (root == nullptr)
            return false;
        path.push_back(root);
        if (root == node)
            return true;
        if (GetPath(root->left, node, path))
            return true;
        if (GetPath(root->right, node, path))
            return true;
        path.pop_back();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if (root == nullptr)
            return nullptr;
        if (root == q || root == p)
            return root;
        vector<TreeNode*>pPath;
        vector<TreeNode*>qPath;
        GetPath(root, p, pPath);
        GetPath(root, q, qPath);
        while (pPath.size() != qPath.size())
        {
            if (pPath.size() > qPath.size())
                pPath.pop_back();
            else
                qPath.pop_back();
        }
        while (pPath[pPath.size() - 1] != qPath[qPath.size() - 1])
        {
            pPath.pop_back();
            qPath.pop_back();
        }
        return pPath[pPath.size() - 1];
    }
};


5. 二叉树搜索树转换成排序双向链表。oj链接

思路1:通过中序遍历的方式将二叉搜索树的结点全部保存下来,然后改变结点指针的指向进而转换为排序双向链表

class Solution {
public:
    void InOrder(TreeNode* root, vector<TreeNode*>& result)
    {
        if (root == nullptr)
            return;
        InOrder(root->left, result);
        result.push_back(root);
        InOrder(root->right, result);
    }
    TreeNode* Convert(TreeNode* pRootOfTree) {
        if (pRootOfTree == nullptr)
            return nullptr;
        vector<TreeNode*>result;
        InOrder(pRootOfTree, result);
        for (int i = 0; i < result.size() - 1; i++)
        {
            result[i]->right = result[i + 1];
            result[i + 1]->left = result[i];
        }
        return result[0];
    }
};

思路2:定义两个指针cur和prev,然后在中序遍历的过程中改变指针的指向:

class Solution {
public:
    void InOrder(TreeNode* cur, TreeNode*& prev)
    {
        if (cur == nullptr)
            return;
        InOrder(cur->left, prev);
        cur->left = prev;
        if (prev)
            prev->right = cur;
        prev = cur;
        InOrder(cur->right, prev);
    }
    TreeNode* Convert(TreeNode* pRootOfTree) 
    {
        TreeNode* prev = nullptr;
        InOrder(pRootOfTree, prev);
        TreeNode* head = pRootOfTree;
        while (head && head->left)
        {
            head = head->left;
        }
        return head;
    }
};


6. 根据一棵树的前序遍历与中序遍历构造二叉树 oj链接

实现思路:前序遍历依次从前往后找根,然后中序遍历找到根在递归左区间构建,然后在递归右区间构造

class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prei, int inbegin, int inend)
    {
        if (inbegin > inend)
        {
            return nullptr;
        }
        int rooti = inbegin;
        while (rooti <= inend)
        {
            if (inorder[rooti] == preorder[prei])
                break;
            rooti++;
        }
        TreeNode* root = new TreeNode(inorder[rooti]);
        prei++;
        root->left = _buildTree(preorder, inorder, prei, inbegin, rooti - 1);
        root->right = _buildTree(preorder, inorder, prei, rooti + 1, inend);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int pi = 0;
        return _buildTree(preorder, inorder, pi, 0, inorder.size() - 1);
    }
};


7. 根据一棵树的中序遍历与后序遍历构造二叉树。oj链接

实现思路:根据后续遍历依次从后往前找根,然后在中序遍历中找根,然后递归构建右子树,再递归构建左子树

class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,int& posti,int inbegin,int inend)
    {
        if (inbegin > inend)
            return nullptr;
        int rooti = inbegin;
        while (rooti <= inend)
        {
            if (inorder[rooti] == postorder[posti])
            {
                break;
            }
            rooti++;
        }
        TreeNode* root = new TreeNode(inorder[rooti]);
        posti--;
        root->right = _buildTree(inorder, postorder, posti, rooti + 1, inend);
        root->left = _buildTree(inorder, postorder, posti, inbegin, rooti - 1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) 
    {
        int posti = postorder.size() - 1;
        return _buildTree(inorder, postorder, posti, 0, inorder.size() - 1);
    }
};


8. 二叉树的前序遍历,非递归迭代实现 。oj链接

实现思路:使用一个栈,循环遍历左子树,将节点加入到栈中,同时将值加入到vector中,然后循环遍历右子树

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*>st;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                v.push_back(cur->val);
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            cur = top->right;
        }
        return v;
    }
};


9. 二叉树中序遍历 ,非递归迭代实现。oj链接

实现思路:使用一个栈,循环遍历左子树,将结点加入到栈中,出栈的时候将结点的值加入到vector中,然后循环遍历右子树

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> v;
        stack<TreeNode*>st;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            v.push_back(top->val);
            cur = top->right;
        }
        return v;
    }
};


10. 二叉树的后序遍历 ,非递归迭代实现。

实现思路:和中序遍历相同,不过在访问根结点的时候,1.右子树为空直接访问根节点,2.根节点的右子树是上一个访问的结点就访问根节点,不然就访问右子树

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>v;
        stack<TreeNode*>st;
        TreeNode* prev = nullptr;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            //1.右子树为空直接访问根节点,2.根节点的右子树是上一个访问的结点就访问根节点
            //不然就访问右子树
            TreeNode* top = st.top();
            if (top->right == nullptr || top->right == prev)
            {
                v.push_back(top->val);
                st.pop();
                prev = top;
            }
            else
            {
                cur = top->right;
            }
        }
        return v;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_65307907/article/details/128880987