二叉树进阶

目录

二叉树进阶

1. 内容安排说明

2. 二叉搜索树

2.1 二叉搜索树概念

2.2 二叉搜索树操作

2.2.1 二叉搜索树的查找

2.2.2 二叉搜索树的插入

2.2.3 二叉搜索树的删除

2.3 二叉搜索树的实现 

2.4 二叉搜索树的应用

2.5 二叉搜索树的性能分析

3. 二叉树进阶面试题


二叉树进阶

1. 内容安排说明

二叉树在前面C数据结构阶段已经讲过,本节取名二叉树进阶是因为:

  1. map和set特性需要先铺垫二叉搜索树,而二叉搜索树也是一种树形结构
  2. 二叉搜索树的特性了解,有助于更好的理解map和set的特性
  3.  二叉树中部分面试题稍微有点难度,在前面讲解大家不容易接受,且时间长容易忘
  4. 有些OJ题使用C语言方式实现比较麻烦,比如有些地方要返回动态开辟的二维数组,非常麻烦。

因此本节借二叉树搜索树,对二叉树部分进行收尾总结

2. 二叉搜索树

2.1 二叉搜索树概念

二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:

  • 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
  • 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
  • 它的左右子树也分别为二叉搜索树

2.2 二叉搜索树操作

int a[] = {8, 3, 1, 10, 6, 4, 7, 14, 13};
2.2.1 二叉搜索树的查找
  1. 从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。
  2. 最多查找高度次,走到到空,还没找到,这个值不存在。
2.2.2 二叉搜索树的插入

插入的具体过程如下:

  1. 树为空,则直接新增节点,赋值给root指针
  2.  树不空,按二叉搜索树性质查找插入位置,插入新节点

2.2.3 二叉搜索树的删除

首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情况:

  1. 要删除的结点无孩子结点
  2. 要删除的结点只有左孩子结点
  3. 要删除的结点只有右孩子结点
  4. 要删除的结点有左、右孩子结点

看起来有待删除节点有4中情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程
如下:

  • 情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点--直接删除
  • 情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点--直接删除
  • 情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题--替换法删除

2.3 二叉搜索树的实现 

#pragma once
#include<iostream>
using namespace std;

template<class K>
class BSTreeNode//定义一个节点
{
public:
	BSTreeNode<K>* _left;
	BSTreeNode<K>* _right;
	K _key;

	BSTreeNode<K>(const K& key)
		:_left(nullptr)
		, _right(nullptr)
		, _key(key)
	{}
};

template<class K>
class BSTree
{
	typedef BSTreeNode<K> Node;
public:
	BSTree(){ }
	~BSTree() { DestroyBSTree(_root);}
	void DestroyBSTree(Node* root)
	{
		if (root == nullptr)
			return;
		DestroyBSTree(root->_left);
		DestroyBSTree(root->_right);
		delete root;
		cout << "void DestroyBSTree(Node* root)" << endl;
	}
public:
	bool Insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			parent = cur;
			if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else
			{
				return false;
			}
		}
		cur = new Node(key);
		if (parent->_key > key)
		{
			parent->_left = cur;
		}
		else
		{
			parent->_right = cur;
		}
		return true;
	}
	bool Find(const K& key)
	{
		if (_root == nullptr)
			return false;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key > key)
			{
				cur = cur->_left;
			}
			else if (cur->_key < key)
			{
				cur = cur->_right;
			}
			else
			{
				return true;
			}
		}
		return false;
	}
	bool Erase(const K& key)
	{
		Node* parent = _root;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_right;
					}
					if (parent->_left == cur)
					{
						parent->_left = cur->_right;
					}
					else
					{
						parent->_right = cur->_right;
					}
				}
				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
					}
					if (parent->_left == cur)
					{
						parent->_left = cur->_left;
					}
					else
					{
						parent->_right = cur->_left;
					}
				}
				else
				{
					parent = cur;
					Node* subLeft = cur->_right;
					while (subLeft->_left)
					{
						parent = subLeft;
						subLeft = subLeft->_left;
					}
					swap(cur->_key, subLeft->_key);
					if (subLeft == parent->_left)
					{
						parent->_left = subLeft->_right;
					}
					else
					{
						parent->_right = subLeft->_right;
					}
				}
				return true;
			}
		}
		return false;

	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
	bool FindR(const K& key)
	{
		return _FindR(_root, key);
	}
	bool InsertR(const K& key)
	{
		return _InsertR(_root, key);
	}
	bool EraseR(const K& key)
	{
		return _EraseR(_root, key);
	}
private:
	bool _EraseR(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			return false;
		}
		if (root->_key > key)
		{
			return _EraseR(root->_left, key);
		}
		else if (root->_key < key)
		{
			return _EraseR(root->_right, key);
		}
		else
		{
			if (root->_left == nullptr)
			{
				Node* del = root;
				root = root->_right;
				delete del;
				return true;
			}
			else if (root->_right == nullptr)
			{
				Node* del = root;
				root = root->_left;
				delete del;
				return true;
			}
			else
			{
				Node* subLeft = root->_right;
				while (subLeft->_left)
				{
					subLeft = subLeft->_left;
				}
				swap(subLeft->_key, root->_key);
				return _EraseR(root->_right, key);
			}
		}
	}
	bool _InsertR(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			root = new Node(key);
			return true;
		}

		if (root->_key > key)
		{
			return _InsertR(root->_left, key);
		}
		else if (root->_key < key)
		{
			return _InsertR(root->_right, key);
		}
		else
		{
			return false;
		}

	}
	bool _FindR(Node* root, const K& key)
	{
		if (root == nullptr)
		{
			return false;
		}
		if (root->_key > key)
		{
			return _FindR(root->_left, key);
		}
		else if (root->_key < key)
		{
			return _FindR(root->_right, key);
		}
		else
		{
			return true;
		}
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
			return;

		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
	}
private:
	Node* _root = nullptr;
};

2.4 二叉搜索树的应用

1. K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值。

比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:

  • 以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树
  • 在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。

2. KV模型:每一个关键码key,都有与之对应的值Value,即<Key, Value>的键值对。该种方式在现实生活中非常常见:

  • 比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文<word, chinese>就构成一种键值对;
  • 再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是<word, count>就构成一种键值对。
#include<iostream>
#include<string>
#include<vector>

using namespace std;

// 改造二叉搜索树为KV结构
template<class K, class V>
struct BSTNode
{

	BSTNode(const K& key = K(), const V& value = V())
		: _left(nullptr), _right(nullptr), _key(key), _value(value)
	{}
	BSTNode<K, V>* _left;
	BSTNode<K, V>* _right;
	K _key;
	V _value;
};
template<class K, class V>
class BSTree
{
	typedef BSTNode<K, V> Node;
public:
	BSTree() : _root(nullptr) {}
	Node* Find(const K& key)
	{
		//...
		return _FindR(_root, key);
	}
	bool Insert(const K& key, const V& value)
	{
		return _InsertR(_root, key, value);
	}
	bool Erase(const K& key)
	{
		return _EraseR(_root, key);
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << "*****" << endl;
		cout << endl;
	}
private:
	Node* _FindR(Node* root, const K& key)
	{
		if (root == nullptr)
		{
			return nullptr;
		}
		if (root->_key > key)
		{
			return _FindR(root->_left, key);
		}
		else if (root->_key < key)
		{
			return _FindR(root->_right, key);
		}
		else
		{
			return root;
		}
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << "  " << root->_value << endl;
		_InOrder(root->_right);
	}
	bool _EraseR(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			return false;
		}
		if (root->_key > key)
		{
			return _EraseR(root->_left, key);
		}
		else if (root->_key < key)
		{
			return _EraseR(root->_right, key);
		}
		else
		{
			if (root->_left == nullptr)
			{
				Node* Del = root;
				root = root->_right;
				delete Del;
				return true;
			}
			else if (root->_right == nullptr)
			{
				Node* Del = root;
				root = root->_left;
				delete Del;
				return true;
			}
			else
			{
				Node* subTree = root->_right;
				while (subTree->_left)
				{
					subTree = subTree->_left;
				}
				swap(subTree, root);
				return _EraseR(root->_right, key);
			}
		}
	}
	void swap(Node* node1, Node* node2)
	{
		std::swap(node1->_key, node2->_key);
		std::swap(node1->_value, node2->_value);
	}
	bool _InsertR(Node*& root, const K& key, const V& value)
	{
		if (root == nullptr)
		{
			root = new Node(key, value);
			return true;
		}
		if (root->_key > key)
		{
			return _InsertR(root->_left, key, value);
		}
		else if (root->_key < key)
		{
			return _InsertR(root->_right, key, value);
		}
		else
		{
			return false;
		}
	}
	Node* _root;
};

void TestBSTree3()
{
	// 输入单词,查找单词对应的中文翻译
	BSTree<string, string> dict;
	dict.Insert("string", "字符串");
	dict.Insert("tree", "树");
	dict.Insert("left", "左边、剩余");
	dict.Insert("right", "右边");
	dict.Insert("sort", "排序");
	// 插入词库中所有单词
	string str;
	while (cin >> str)
	{
		BSTNode<string, string>* ret = dict.Find(str);
		if (ret == nullptr)
		{
			cout << "单词拼写错误,词库中没有这个单词:" << str << endl;
		}
		else
		{
			cout << str << "中文翻译:" << ret->_value << endl;
		}
	}
}

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

2.5 二叉搜索树的性能分析

插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。

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

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

最优情况下,二叉搜索树为完全二叉树(或者接近完全二叉树),其平均比较次数为:$log_2 N$
最差情况下,二叉搜索树退化为单支树(或者类似单支),其平均比较次数为:$\frac{N}{2}$

问题:如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插入关键码,二叉搜索树的性能都能达到最优?那么我们后续章节学习的AVL树和红黑树就可以上场了。

3. 二叉树进阶面试题

根据二叉树创建字符串

class Solution 
{
public:
    string tree2str(TreeNode* root) 
    {
        string s;
        if(root == nullptr)
        {
            return s;
        }

        s += to_string(root->val);
        if(root->left || root->right)//左右为空,括号省略;左为空,右不为空,括号不能省略;左不为空,右为空,
        //括号不能省略
        {
            s += "(";
            s += tree2str(root->left);
            s += ")";
        }

        if(root->right)//右为空,括号省略;
        {
            s += "(";
            s += tree2str(root->right);
            s += ")";
        }
        
        return s;
    }
};

二叉树的分层遍历

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

二叉树的层序遍历2

class Solution 
{
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) 
    {
        vector<vector<int>> vv;
        if(!root)
        {
            return vv;
        }
        queue<TreeNode*> q;
        int size = 0;
        q.push(root);
        ++size;
        while(!q.empty())
        {
            vector<int> v;
            while(size--)
            {
                TreeNode* cur = q.front();
                v.push_back(cur->val);
                q.pop();
                if(cur->left)
                    q.push(cur->left);
                if(cur->right)
                    q.push(cur->right);
            }
            size = q.size();
            vv.push_back(v);
        }
        vector<vector<int>> vv2;
        for(int i = vv.size() - 1; i >= 0; --i)
        {
            vv2.push_back(vv[i]);
        }
        return vv2;
    }
};

二叉树的最近公共祖先

// class Solution //方法1
// {
// public:
//     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
//     {
//         if(!root || root == p || root == q) return root;
//         TreeNode* left = lowestCommonAncestor(root->left, p, q);
//         TreeNode* right = lowestCommonAncestor(root->right, p, q);
//         if(left && right) return root;
//         if(left) return left;
//         if(right) return right;
//         return nullptr;
//     }
// };

class Solution   //方法2
{
public:
    bool FindPath(TreeNode* root, TreeNode* x, stack<TreeNode*>& st)
    {
        if(root == nullptr)
            return false;
        st.push(root);
        if(st.top() == x)
            return true;
        if(FindPath(root->left, x, st))
            return true;
        if(FindPath(root->right, x, st))
            return true;
        st.pop();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        stack<TreeNode*> pPath,qPath;
        FindPath(root, p, pPath);
        FindPath(root, q, qPath);
        while(pPath.size() != qPath.size())
        {
            if(pPath.size() > qPath.size())
            {
                pPath.pop();
            }
            else
            {
                qPath.pop();
            }
        }

        while(pPath.top() != qPath.top())
        {
            pPath.pop();
            qPath.pop();
        }

        return pPath.top();
    }
};

 二叉搜索树与双向链表

class Solution 
{
public:
    TreeNode* Convert(TreeNode* pRootOfTree) 
	{
        if(pRootOfTree == nullptr)
        {
            return nullptr;
        }
        Convert(pRootOfTree->left);
        if(prev == nullptr)
        {
            prev = cur = pRootOfTree;
        }
        else
        {
            prev->right = pRootOfTree;
            pRootOfTree->left = prev;
            prev = pRootOfTree;
        }
        Convert(pRootOfTree->right);
        return cur;
    }
private:
    TreeNode* cur = nullptr;
    TreeNode* prev = nullptr;
};

从前序与中序遍历序列构造二叉树

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

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
        int i = 0;
        TreeNode* root = _buildTree(preorder, inorder, i, 0, inorder.size() - 1);
        return root;
    }
};

从中序与后序遍历序列构造二叉树

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

二叉树的前序遍历

class Solution 
{
public:
    vector<int> preorderTraversal(TreeNode* root) 
    {
        TreeNode* cur = root;
        vector<int> v;
        stack<TreeNode*> st;
        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;
    }
};

二叉树的中序遍历

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

二叉树的后序遍历

class Solution 
{
public:
    vector<int> postorderTraversal(TreeNode* root) 
    {
        vector<int> v;
        stack<TreeNode*> st;
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        while(cur || !st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            if(top->right == nullptr || top->right == prev)
            {
                v.push_back(top->val);
                prev = top;
                st.pop();
            }
            else
            {
                cur = top->right;
            }
        }
        return v;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值