C++:二叉树进阶

✨✨✨学习的道路很枯燥,希望我们能并肩走下来!

文章目录

文章目录

前言

一  二叉搜索树

1.1 二叉搜索树概念

1.2 二叉搜索树操作 

1.2.1 二叉搜索树的查找 

1.2.2 二叉搜索树的插入 

​编辑 1.2.3 二叉搜索树的删除

1.3 二叉搜索树的实现 

1.4 二叉搜索树的应用

1.5 二叉搜索树的性能分析 

二. 二叉树进阶面试题

2.1 二叉树创建字符串

 2.2 二叉树的分层遍历1

 2.3 二叉树的分层遍历2

2.4 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 。 

2.5 二叉树搜索树转换成排序双向链表

2.6 根据一棵树的前序遍历与中序遍历构造二叉树

2.7 根据一棵树的中序遍历与后序遍历构造二叉树

2.8 二叉树的前序遍历,非递归迭代实现 

2.9 二叉树中序遍历 ,非递归迭代实现 

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

总结


前言

本篇详细介绍了进一步介绍C++中的二叉树进阶,让使用者对智能指针有更加深刻的认知,而不是仅仅停留在表面,更好的模拟,为了更好的使用. 文章可能出现错误,如有请在评论区指正,让我们一起交流,共同进步!


一  二叉搜索树

1.1 二叉搜索树概念

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

  若它的左子树不为空,则左子树上所有节点的值都小于根节点的值 

●  若它的右子树不为空,则右子树上所有节点的值都大于根节点的值

●  它的左右子树也分别为二叉搜索树

1.2 二叉搜索树操作 

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

1.2.1 二叉搜索树的查找 

        a、从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。

        b、最多查找高度次,走到到空,还没找到,这个值不存在。 

1.2.2 二叉搜索树的插入 

插入的具体过程如下:

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

        b. 树不空,按二叉搜索树性质查找插入位置,插入新节点 

 1.2.3 二叉搜索树的删除

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

        a. 要删除的结点无孩子结点

        b. 要删除的结点只有左孩子结点

        c. 要删除的结点只有右孩子结点

        d. 要删除的结点有左、右孩子结点 

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

●  情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点--直接删除

●  情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点--直接删除

●  情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点 中,再来处理该结点的删除问题--替换法删除 

1.3 二叉搜索树的实现 

根据上面二叉搜索数的特性,我们可以自己实现一个二叉搜索树 

template<class K, class V>
struct BSTreeNode
{
	BSTreeNode(const K& key, const V& val)
		:_key(key)
		,_val(val)
		,left(nullptr)
		,right(nullptr)
	{}

	K _key;
	V _val;
	BSTreeNode<K, V>* left;
	BSTreeNode<K, V>* right;

};

template<class K, class V>
class BSTree
{
	typedef BSTreeNode<K, V> Node;
public:
	bool Insert(const K& key, const V& value)
	{
		if (_root == nullptr)
		{
			_root = new Node(key, value);
			return true;
		}
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (cur->_key > key)
			{
				parent = cur;
				cur = cur->left;
			}
			else if (cur->_key < key)
			{
				parent = cur;
				cur = cur->right;
			}
			else
				return false;
		}

		cur = new Node(key, value);
		if (parent->_key > key)
		{
			parent->left = cur;
		}
		else
		{
			parent->right = cur;
		}

		return true;

	}
	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key > key)
			{
				cur = cur->left;
			}
			else if (cur->_key < key)
			{
				cur = cur->right;
			}
			else
			{
				return cur;
			}
		}
		return nullptr;
	}
	bool Erase(const K& key)
	{
		Node* cur = _root;
		Node* parent = nullptr;
		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 (parent == nullptr)
					{
						_root = cur->right;
					}
					else
					{
						if (parent->_left == cur)
							parent->_left = cur->_right;
						else
							parent->_right = cur->_right;
					}
				}
				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;
					}
				}
				else
				{
					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;
				}
			}
		}
	}
	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
	void TestBSTree()
	{
		
		string strs[] = { "苹果", "西瓜", "苹果", "樱桃", "苹果", "樱桃", "苹果", "樱桃", "苹果" };
		// 统计水果出现的次
		BSTree<string, int> countTree;
		for (auto str : strs)
		{
			auto ret = countTree.Find(str);
			if (ret == NULL)
			{
				countTree.Insert(str, 1);
			}
			else
			{
				ret->_val++;
			}
		}
		countTree.InOrder();
	}
private:
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->left);
		cout << root->_key << ":" << root->_val << endl;
		_InOrder(root->right);
	}
	Node* _root = nullptr;
};

1.4 二叉搜索树的应用

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

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

        ○  以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树

        ○  在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。 

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

        ○  比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英 文单词与其对应的中文就构成一种键值对;

        ○  再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出 现次数就是就构成一种键值对。  

1.5 二叉搜索树的性能分析 

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

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

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

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

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

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

二. 二叉树进阶面试题

2.1 二叉树创建字符串

606. 根据二叉树创建字符串 - 力扣(LeetCode)

class Solution {
public:
    string tree2str(TreeNode* root) {
        if(root == nullptr)
            return "";
        if(root->left == nullptr && root->right == nullptr)
            return to_string(root->val);
        if(root->right == nullptr)
            return to_string(root->val) + "(" + tree2str(root->left) + ")";
        
        return to_string(root->val) + "(" + tree2str(root->left) + ")(" + tree2str(root->right) + ")";
    }
};

 2.2 二叉树的分层遍历1

102. 二叉树的层序遍历 - 力扣(LeetCode)

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        queue<TreeNode*> q;
        int LevelSize = 0;
        if(root)
        {
            LevelSize = 1;
            q.push(root);
        }
        
        while(LevelSize>0)
        {
            vector<int> v;
            while(LevelSize--)
            {
                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);
            }
            LevelSize = q.size();
            ret.push_back(v);
        }

        return ret;
    }
};

 2.3 二叉树的分层遍历2

107. 二叉树的层序遍历 II - 力扣(LeetCode)

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ret;
        queue<TreeNode*> q;
        int LevelSize = 0;
        if(root)
        {
            LevelSize = 1;
            q.push(root);
        }
        
        while(LevelSize>0)
        {
            vector<int> v;
            while(LevelSize--)
            {
                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);
            }
            LevelSize = q.size();
            ret.push_back(v);
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};

2.4 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 。 

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

解法一: 

class Solution {
public:
    bool Getpath(TreeNode* root, TreeNode* t, stack<TreeNode*>&path)
    {
        if(root == nullptr)
            return false;
        path.push(root);
        if(root == t)
            return true;
        if(Getpath(root->left,t,path))
            return true;
        if(Getpath(root->right,t,path))
            return true;
        path.pop();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> pPath;
        stack<TreeNode*> qPath;
        Getpath(root,p,pPath);
        Getpath(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:
    bool Isin(TreeNode* t, TreeNode* r)
    {
        if(t == nullptr)
            return false;
        return t == r || Isin(t->left,r) || Isin(t->right,r);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr)
            return nullptr;
        if(p == root || q == root)
            return root;

        bool pIsLeft = Isin(root->left,p);
        bool pIsRight = !pIsLeft;

        bool qIsLeft = Isin(root->left,q);
        bool qIsRight = !qIsLeft;

        if(qIsLeft&&pIsRight || pIsLeft&&qIsRight)
            return root;
        else if(pIsLeft&&qIsLeft)
            return lowestCommonAncestor(root->left,p,q);
        else
            return lowestCommonAncestor(root->right,p,q);


    }
};

2.5 二叉树搜索树转换成排序双向链表

二叉搜索树与双向链表_牛客题霸_牛客网 (nowcoder.com)

#include <cstddef>
class Solution {
public:
	void InOrderConvert(TreeNode* cur,TreeNode*& prev)
	{
		if(cur == nullptr)
			return;
		InOrderConvert(cur->left,prev);
		cur->left = prev;
		if(prev)
			prev->right = cur;
		prev = cur;
		InOrderConvert(cur->right,prev);
	}
    TreeNode* Convert(TreeNode* pRootOfTree) {
		if(pRootOfTree == nullptr)
			return nullptr;
		TreeNode* prev = nullptr;
        InOrderConvert(pRootOfTree,prev);

		TreeNode* head = pRootOfTree;
		while(head->left)
		{
			head = head->left;
		}
		return head;
    }
};

2.6 根据一棵树的前序遍历与中序遍历构造二叉树

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prei, int inbegin, int inend)
    {
        if(inbegin > inend)
            return nullptr;
        
        // 前序确定根
        TreeNode* root = new TreeNode(preorder[prei++]);

        // 根分割中序左右⼦区间
        int rooti = inbegin;
        while(rooti <= inend)
        {
            if(inorder[rooti] == root->val)
                break;
            else
                rooti++;
        }
        // 递归左右⼦区间,递归构建左右⼦树
        // [inbegin, rooti-1] rooti [rooti+1, inend]
        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 prei = 0;
        return _buildTree(preorder,inorder,prei,0,inorder.size()-1);
    }
};

2.7 根据一棵树的中序遍历与后序遍历构造二叉树

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder, int& prei, int inbegin, int inend)
    {
        if(inbegin > inend)
            return nullptr;
        
        // 前序确定根
        TreeNode* root = new TreeNode(postorder[prei--]);

        // 根分割中序左右⼦区间
        int rooti = inbegin;
        while(rooti <= inend)
        {
            if(inorder[rooti] == root->val)
                break;
            else
                rooti++;
        }
        // 递归左右⼦区间,递归构建左右⼦树
        // [inbegin, rooti-1] rooti [rooti+1, inend]
        root->right = _buildTree(inorder,postorder,prei,rooti+1,inend);
        root->left = _buildTree(inorder,postorder,prei,inbegin,rooti-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        //将后序当作前序,先构造右子树
        int i = postorder.size()-1;
        return _buildTree(inorder,postorder,i,0,inorder.size()-1);
    }
};

2.8 二叉树的前序遍历,非递归迭代实现 

144. 二叉树的前序遍历 - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        TreeNode* cur = root;
        vector<int> v;

        while(cur || !st.empty())
        {
            //每次循环开始代码访问一棵树的开始
            //访问左路节点,左路节点入栈
            while(cur)
            {
                st.push(cur);
                v.push_back(cur->val);
                cur = cur->left;
            }
            //取一个左路节点出来访问
            TreeNode* top = st.top();
            st.pop();

            //循环子问题的访问访问右子树
            cur = top->right;
        }

        return v;

    }
};

2.9 二叉树中序遍历 ,非递归迭代实现 

94. 二叉树的中序遍历 - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        TreeNode* cur = root;
        stack<TreeNode*> st;
        vector<int> v;

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

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

145. 二叉树的后序遍历 - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        stack<TreeNode*> st;
        vector<int> v;
        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);
                st.pop();
                prev = top;
            }
            else
            {
                cur = top->right;
            }
        }
        return v;
    }
};

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

  • 18
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值