欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++二叉搜索樹(shù)BSTree使用詳解

 更新時(shí)間:2023年03月09日 08:30:11   作者:平凡的人1  
二叉搜索樹(shù)(Binary Search Tree)又稱(chēng)二叉排序樹(shù),也稱(chēng)作二叉查找樹(shù)它或者是一棵空樹(shù),或者是具有以下性質(zhì)的二叉樹(shù),若它的左子樹(shù)不為空,則左子樹(shù)上所有節(jié)點(diǎn)的值都小于根節(jié)點(diǎn)的值,若它的右子樹(shù)不為空,則右子樹(shù)上所有節(jié)點(diǎn)的值都大于根節(jié)點(diǎn)的值

一、概念

二叉搜索樹(shù)又稱(chēng)二叉排序樹(shù),它或者是一棵空樹(shù),或者是具有以下性質(zhì)的二叉樹(shù):

若它的左子樹(shù)不為空,則左子樹(shù)上所有節(jié)點(diǎn)的值都小于根節(jié)點(diǎn)的值

若它的右子樹(shù)不為空,則右子樹(shù)上所有節(jié)點(diǎn)的值都大于根節(jié)點(diǎn)的值

左<根<右

它的左右子樹(shù)也分別為二叉搜索樹(shù)

之所以又叫二叉排序樹(shù),是因?yàn)槎嫠阉鳂?shù)中序遍歷的結(jié)果是有序的

二、基礎(chǔ)操作

1.查找find

基于二叉搜索樹(shù)的特點(diǎn),查找一個(gè)數(shù)并不難,若根節(jié)點(diǎn)不為空的情況下:

若根節(jié)點(diǎn)key==查找key,直接返回true

若根節(jié)點(diǎn)key>查找key,那得找到更小的,則往左子樹(shù)查找

若根節(jié)點(diǎn)key<查找key,那得找到更大的,則往右子樹(shù)查找

最多查找高度次,走到空為止,如果還沒(méi)找到,則說(shuō)明這個(gè)值不存在,返回false

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

2.插入Insert

1.樹(shù)為空,則直接插入,新增節(jié)點(diǎn),直接插入root指針即可

2.樹(shù)不為空,按二叉搜索樹(shù)性質(zhì)查找插入位置,插入新節(jié)點(diǎn)。

(注意:不能插入重復(fù)的元素,并且每次插入都是要定位到空節(jié)點(diǎn)的位置;我們先定義一個(gè) cur從root開(kāi)始,比較元素的大?。喝舨迦氲脑乇犬?dāng)前位置元素小就往左走,比當(dāng)前位置元素大就往右走,直到為空,相等就不能插入了;同時(shí)定義一個(gè)parent去記錄當(dāng)前 cur的前一個(gè)位置,最后判斷cur是parent的左子樹(shù)還是右子樹(shù)即可)

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

3.中序遍歷InOrder

遞歸走起,同時(shí)由于_root是私有的,外部不能訪(fǎng)問(wèn),我們可以在類(lèi)內(nèi)給中序提供一個(gè)方法即可,就不需要傳參了

void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}
private:
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << " ";
		_InOrder(root->_right);
	}
	Node* _root = nullptr;

4.刪除erase

刪除的情況比較多:

  • 左右都為空:葉子結(jié)點(diǎn),直接置空并鏈接到空指針
  • 左為空或右為空:進(jìn)行托孤:只有一個(gè)子節(jié)點(diǎn),刪除自己本身,并鏈接子節(jié)點(diǎn)和父節(jié)點(diǎn)(注意:如果父親是空,也就是要?jiǎng)h除根結(jié)點(diǎn),此時(shí)根節(jié)點(diǎn)沒(méi)有父親,單獨(dú)判斷一下)
  • 左右都不為空:找出替換節(jié)點(diǎn):右子樹(shù)最小節(jié)點(diǎn)**、**左子樹(shù)最大節(jié)點(diǎn)。替換節(jié)點(diǎn)可以作為交換和刪除進(jìn)行交換,交換后刪除交換節(jié)點(diǎn)、交換節(jié)點(diǎn)要么沒(méi)有孩子,要么只有一個(gè)孩子可以直接刪除

但是左右都為空可以納入到左為空或右為空的情況

注意:

代碼實(shí)現(xiàn):

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
			{
				//左為空
				if (cur->_left == nullptr)
				{
					//刪除根結(jié)點(diǎn)
					//if(parent==nullptr)
					if (cur == _root)
					{
						_root = cur->_right;
					}
					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_right;
						}
						else
						{
							parent->_right = cur->_right;
						}
					}
					delete cur;
				}
				//右為空
				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
					}
					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_left;
						}
						else
						{
							parent->_right = cur->_left;
						}
					}
					delete cur;
				}
				//左右都不為空,找替換節(jié)點(diǎn)
				else
				{
					//不能初始化為nullptr
					Node* parent = cur;
					//右子樹(shù)最小節(jié)點(diǎn)
					Node* minRight = cur->_right;
					while (minRight->_left)
					{
						parent = minRight;
						minRight = minRight->_left;
					}
					cur->_key = minRight->_key;
					//判斷minRight是父親的左還是右
					if (minRight == parent->_left)
					{
						parent->_left = minRight->_right;
					}
					else
					{
						parent->_right = minRight->_right;
					}
					delete minRight;
				}
				return true;
			}
		}
		return false;
	}

三、遞歸寫(xiě)法

1.遞歸查找

這個(gè)比較簡(jiǎn)單:蘇醒把,遞歸時(shí)刻

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

2.遞歸插入

最大的問(wèn)題是插入之后跟父親進(jìn)行鏈接,如果直接給root是不可以的,因?yàn)閞oot是棧幀里面的參數(shù),只是局部變量:加上引用

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

3.遞歸刪除

遞歸刪除怎么找到父節(jié)點(diǎn)?root = root->_left/ root = root->_right;

bool _EraseR(Node*& root, const K& key)
	{
		if (root == nullptr)
		{
			return false;
		}
		if (root->_key < key)
		{
			return _EraseR(root->_right, key);
		}
		else if (root->_key > key)
		{
			return _EraseR(root->_left, key);
		}
		else
		{
			Node* del = root;
			if (root->_right == nullptr)
			{
				root = root->_left;
			}
			else if (root->_left == nullptr)
			{
				root = root->_right;
			}
			else
			{
				Node* minRight = root->_right;
				while (minRight->_left)
				{
					minRight = minRight->_left;
				}
				swap(root->_key, minRight->_key);
				return _EraseR(root->_right, key);
			}
			delete del;
			return true;
		}
	}

四、應(yīng)用

最優(yōu)情況下,二叉搜索樹(shù)為完全二叉樹(shù),其平均比較次數(shù)為:log2N

最差情況下,二叉搜索樹(shù)退化為單支樹(shù),其平均比較次數(shù)為: N/2

1.K模型:K模型即只有key作為關(guān)鍵碼,結(jié)構(gòu)中只需要存儲(chǔ)Key即可,關(guān)鍵碼即為需要搜索到的值,判斷關(guān)鍵字是否存在。

比如:給一個(gè)單詞word,判斷該單詞是否拼寫(xiě)正確,具體方式如下:

以單詞集合中的每個(gè)單詞作為key,構(gòu)建一棵二叉搜索樹(shù),在二叉搜索樹(shù)中檢索該單詞是否存在,存在則拼寫(xiě)正確,不存在則拼寫(xiě)錯(cuò)誤。

2.KV模型:每一個(gè)關(guān)鍵碼key,都有與之對(duì)應(yīng)的值Value,即**<Key, Value>**的鍵值對(duì)。

比如英漢詞典就是英文與中文的對(duì)應(yīng)關(guān)系,通過(guò)英文可以快速找到與其對(duì)應(yīng)的中文,英文單詞與其對(duì)應(yīng)的中文<word, chinese>就構(gòu)成一種鍵值對(duì);再比如統(tǒng)計(jì)單詞次數(shù),統(tǒng)計(jì)成功后,給定單詞就可快速找到其出現(xiàn)的次數(shù),單詞與其出現(xiàn)次數(shù)就是**<word, count>**就構(gòu)成一種鍵值對(duì)。

namespace KV
{
	template <class K,class V>
	struct BSTreeNode
	{
		BSTreeNode<K,V>* _left;
		BSTreeNode<K,V>* _right;
		K _key;
		V _value;
		BSTreeNode(const K& key,const V&value)
			:_key(key),
			_value(value),
			_left(nullptr),
			_right(nullptr)
		{}
	};
	template <class K,class V>
	class BSTree
	{
        typedef BSTreeNode<K, V> Node;
	public:
		bool Insert(const K& key, const V& value)
		Node* find(const K& key)
		void InOrder()
	private:
		Node* _root = nullptr;
	};
}
void TestBSTree()
{
	//key/Value的搜索模型;通過(guò)key查找或修改Value
	KV::BSTree<string, string> dict;
	dict.Insert("sort", "排序");
	dict.Insert("string", "字符串");
	dict.Insert("left", "左");
	dict.Insert("right", "右");
	string str;
	while (cin >> str)
	{
		KV::BSTreeNode<string, string>* ret = dict.find(str);
		if (ret)
		{
			cout << ret->_value << endl;
		}
		else
		{
			cout << "找不到" << endl;
		}
	}
}

源代碼:

BSTree.h

#include <iostream>
using namespace std;
namespace K
{
	template <class K>
	struct BSTreeNode
	{
		BSTreeNode<K>* _left;
		BSTreeNode<K>* _right;
		K _key;
		BSTreeNode(const K& key)
			:_key(key),
			_left(nullptr),
			_right(nullptr)
		{}
	};
	template <class K>
	class BSTree
	{
		typedef BSTreeNode<K> Node;
	public:
		BSTree()
			:_root(nullptr)
		{}
		BSTree(const BSTree<K>& t)
		{
			_root = Copy(t._root);
		}
		BSTree<K>& operator = (BSTree<K> t)
		{
			swap(_root, t._root);
			return *this;
		}
		~BSTree()
		{
			Destroy(_root);
			_root = nullptr;
		}
		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
				{
					//左為空
					if (cur->_left == nullptr)
					{
						//刪除根結(jié)點(diǎn)
						//if(parent==nullptr)
						if (cur == _root)
						{
							_root = cur->_right;
						}
						else
						{
							if (parent->_left == cur)
							{
								parent->_left = cur->_right;
							}
							else
							{
								parent->_right = cur->_right;
							}
						}
						delete cur;
					}
					//右為空
					else if (cur->_right == nullptr)
					{
						if (cur == _root)
						{
							_root = cur->_left;
						}
						else
						{
							if (parent->_left == cur)
							{
								parent->_left = cur->_left;
							}
							else
							{
								parent->_right = cur->_left;
							}
						}
						delete cur;
					}
					//左右都不為空,找替換節(jié)點(diǎn)
					else
					{
						//不能初始化為nullptr
						Node* parent = cur;
						//右子樹(shù)最小節(jié)點(diǎn)
						Node* minRight = cur->_right;
						while (minRight->_left)
						{
							parent = minRight;
							minRight = minRight->_left;
						}
						cur->_key = minRight->_key;
						//判斷minRight是父親的左還是右
						if (minRight == parent->_left)
						{
							parent->_left = minRight->_right;
						}
						else
						{
							parent->_right = minRight->_right;
						}
						delete minRight;
					}
					return true;
				}
			}
			return false;
		}
		void InOrder()
		{
			_InOrder(_root);
			cout << endl;
		}
        //遞歸
		bool InsertR(const K& key)
		{
			return _InsertR(_root, key);
		}
		bool FindR(const K& key)
		{
			return _FindR(_root, key);
		}
		bool EraseR(const K& key)
		{
			return _EraseR(_root, key);
		}
	private:
		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* newRoot = new Node(root->_key);
			newRoot->_left = Copy(root->_left);
			newRoot->_right = Copy(root->_right);
			return newRoot;
		}
		bool _EraseR(Node*& root, const K& key)
		{
			if (root == nullptr)
			{
				return false;
			}
			if (root->_key < key)
			{
				return _EraseR(root->_right, key);
			}
			else if (root->_key > key)
			{
				return _EraseR(root->_left, key);
			}
			else
			{
				Node* del = root;
				if (root->_right == nullptr)
				{
					root = root->_left;
				}
				else if (root->_left == nullptr)
				{
					root = root->_right;
				}
				else
				{
					Node* minRight = root->_right;
					while (minRight->_left)
					{
						minRight = minRight->_left;
					}
					swap(root->_key, minRight->_key);
					return _EraseR(root->_right, key);
				}
				delete del;
				return true;
			}
		}
		bool _InsertR(Node*& root, const K& key)
		{
			if (root == nullptr)
			{
				root = new Node(key);
				return true;
			}
			else if (root->_key < key)
				return _InsertR(root->_right, key);
			else if (root->_key > key)
				return _InsertR(root->_left, key);
			else
				return false;
		}
		bool _FindR(Node* root, const K& key)
		{
			if (root == nullptr) return false;
			else if (root->_key < key) return _FindR(root->_right, key);
			else if (root->_key > key) return _FindR(root->_left, key);
			else return true;
		}
		void _InOrder(Node* root)
		{
			if (root == nullptr)
			{
				return;
			}
			_InOrder(root->_left);
			cout << root->_key << " ";
			_InOrder(root->_right);
		}
		Node* _root = nullptr;
	};
}
namespace KV
{
	template <class K,class V>
	struct BSTreeNode
	{
		BSTreeNode<K,V>* _left;
		BSTreeNode<K,V>* _right;
		K _key;
		V _value;
		BSTreeNode(const K& key,const V&value)
			:_key(key),
			_value(value),
			_left(nullptr),
			_right(nullptr)
		{}
	};
	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* 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, value);
			if (parent->_key < key)
			{
				parent->_right = cur;
			}
			else
			{
				parent->_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);
		}
	private:
		void _InOrder(Node* root)
		{
			if (root == nullptr) return;
			_InOrder(root->_left);
			cout << root->_key << ":"<<root->_value<<endl;
			_InOrder(root->_right);
		}
		Node* _root = nullptr;
	};
}
void TestBSTree1()
{
	int a[] = { 8, 3, 1, 10, 6, 4, 7, 14, 13 };
	K::BSTree<int> t;
	for (auto e : a)
	{
		t.Insert(e);
	}
	t.InOrder();
	K::BSTree<int> copyt(t);
	copyt.InOrder();
	t.InsertR(9);
	t.InOrder();
	t.EraseR(9);
	t.InOrder();
	t.EraseR(3);
	t.InOrder();
	for (auto e : a)
	{
		t.EraseR(e);
	    t.InOrder();
	}
}
void TestBSTree2()
{
	KV::BSTree<string, string> dict;
	dict.Insert("sort", "排序");
	dict.Insert("string", "字符串");
	dict.Insert("left", "左");
	dict.Insert("right", "右");
	string str;
	while (cin >> str)
	{
		KV::BSTreeNode<string, string>* ret = dict.find(str);
		if (ret)
		{
			cout << ret->_value << endl;
		}
		else
		{
			cout << "找不到" << endl;
		}
	}
}
void TestBSTree3()
{
	string arr[] = { "蘋(píng)果","西瓜","蘋(píng)果" };
	KV::BSTree<string, int> countTree;
	for (auto e : arr)
	{
		auto* ret = countTree.find(e);
		if (ret == nullptr)
		{
			countTree.Insert(e, 1);
		}
		else
		{
			ret->_value++;
		}
	}
	countTree.InOrder();
}
#include "BSTree.h"
int main()
{
    //TestBSTree1();
	TestBSTree2();
    //TestBSTree3();
	return 0;
}

五、題目練習(xí)

根據(jù)二叉樹(shù)創(chuàng)建字符串

前序遍歷,左為空,右不為空的括號(hào)不可以省略,右為空的括號(hào)可以省略

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

二叉樹(shù)的層序遍歷

層序遍歷,可以通過(guò)一個(gè)隊(duì)列來(lái)實(shí)現(xiàn),同時(shí)定義每次隊(duì)列的大小

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

二叉樹(shù)的最近公共祖先

class Solution {
    bool isInTree(TreeNode*root,TreeNode*x)
    {
        if(root == nullptr) return false;
        if(root == x) return true;
        else 
            return isInTree(root->left,x)
                || isInTree(root->right,x);
    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr)
            return nullptr;
        if(root == p||root==q) return root;
        bool pLeft = isInTree(root->left,p);
        bool pRight = !pLeft;
        bool qLeft = isInTree(root->left,q);
        bool qRight = !qLeft;
        //一個(gè)在左一個(gè)在右
        if((pLeft&&qRight)||(pRight&&qLeft))
            return root;
        //同左
        if(pLeft&&qLeft)
            return lowestCommonAncestor(root->left,p,q);
        //同右
        else
            return lowestCommonAncestor(root->right,p,q);
    }
};

把根到對(duì)應(yīng)節(jié)點(diǎn)的路徑存儲(chǔ)起來(lái),在找出相交的結(jié)點(diǎn)即是最近的公共結(jié)點(diǎn):

class Solution {
    bool GetPath(TreeNode*root,TreeNode*x,stack<TreeNode*>& stack)
    {
        if(root == nullptr) return false;
        stack.push(root);
        if(root == x)
        {
            return true;
        }
        if(GetPath(root->left,x,stack))
            return true;
        if(GetPath(root->right,x,stack))
            return true;
        stack.pop();
        return false;
    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr)
            return nullptr;
        stack<TreeNode*> pPath;
        stack<TreeNode*> qPath;
        GetPath(root,p,pPath);
        GetPath(root,q,qPath);
        //長(zhǎng)的先pop
        while(pPath.size()!=qPath.size())
        {
            if(pPath.size()>qPath.size())
            {
                pPath.pop();
            }
            else
                qPath.pop();
        }
        //同時(shí)pop,找出交點(diǎn)
        while(pPath.top()!=qPath.top())
        {
            pPath.pop();
            qPath.pop();
        }
        return pPath.top();
    }
};

二叉搜索樹(shù)與雙向鏈表

思路一:中序遍歷,將節(jié)點(diǎn)放到一個(gè)vector中,在鏈接節(jié)點(diǎn),但是空間復(fù)雜度不符合題目要求:

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

思路二:遞歸直接進(jìn)行轉(zhuǎn)換

class Solution {
	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);
	}
public:
    TreeNode* Convert(TreeNode* pRootOfTree) {
		TreeNode*prev = nullptr;
		InOrder(pRootOfTree,prev);
		//找頭
		TreeNode*head = pRootOfTree;
		while(head&&head->left)
		{
			head = head->left;
		}
		return head;
	}
};

從前序與中序遍歷序列構(gòu)造二叉樹(shù)

根據(jù)前序結(jié)果去創(chuàng)建樹(shù),前序是根左右,前序第一個(gè)元素就是根,在通過(guò)中序去進(jìn)行分割左右子樹(shù)。子樹(shù)區(qū)間確認(rèn)是否繼續(xù)遞歸創(chuàng)建子樹(shù),區(qū)間不存在則是空樹(shù)。所以根據(jù)前序先構(gòu)造根,在通過(guò)中序構(gòu)造左子樹(shù)、在構(gòu)造右子樹(shù)即可。

class Solution {
    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(inbegin<=inend)
        {
            if(preorder[prei] == inorder[rooti])
            {
                break;
            }
            else rooti++;
        }
        prei++;
        //[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;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int prei = 0;
       return _buildTree(preorder,inorder,prei,0,inorder.size()-1);
    }
};

傳引用問(wèn)題:因?yàn)閜rei是遍歷前序數(shù)組開(kāi)始的下標(biāo),整個(gè)遞歸遍歷中都要使用,所以我們需要傳引用。如果不是傳引用而是傳值的話(huà),左子樹(shù)構(gòu)建好返回,如果此時(shí)prei不是傳引用,只是形參,無(wú)法將上一次遞歸的結(jié)果保留下來(lái),那么也就無(wú)構(gòu)建右子樹(shù)了。

從中序與后序遍歷序列構(gòu)造二叉樹(shù)

根據(jù)后序遍歷的最后一個(gè)元素可以確定根結(jié)點(diǎn),有了根結(jié)點(diǎn)做為切割點(diǎn)然后再去根據(jù)中序遍歷劃分左右區(qū)間,在繼續(xù)下去,構(gòu)造成二叉樹(shù),區(qū)間不存在就是空樹(shù)了。同時(shí),后序遍歷是左右根,所以最后一個(gè)是根節(jié)點(diǎn)。所以當(dāng)我們構(gòu)造根結(jié)點(diǎn)后,由于前面是右子樹(shù),所以先構(gòu)造右子樹(shù),在構(gòu)造左子數(shù)。

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

到此這篇關(guān)于C++二叉搜索樹(shù)BSTree使用詳解的文章就介紹到這了,更多相關(guān)C++二叉搜索樹(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論