目录
②二叉搜索树的插入(可以做到自动去重、自动排序(对于中序遍历来说,中序遍历是升序))
②二叉搜索树的插入(可以做到自动去重、自动排序(对于中序遍历来说,中序遍历是升序))
②.KV模型(由K模型改写而来。每个key对应一个value,存的是一个个键值对,找到对应的key,对其value进行操作):
一、二叉搜索树
1.二叉搜索树的概念及性质
二叉搜索树又称二叉排序树,它可以是一棵空树,若不是空树,还具有以下性质:
基本属性:
a.若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
b.若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
c.它的左右子树也分别为二叉搜索树
衍生属性:
d.二叉搜索树不支持修改,因为修改之后会改变二叉搜索树的条件,使其变成非二叉搜索树。
e.二叉搜索树不能有重复的值,不支持重复值的搜索。在插入的时候会做到自动去重。
f.二叉搜索树的中序遍历InOder是升序的。
2.二叉搜索树的操作及功能的实现(非递归版本)
①. 二叉搜索树的查找
时间复杂度:O(N)
a、从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。
b、最多查找高度次,走到到空,还没找到,这个值不存在
例:对象.Find(6);
示意图展示:
效果展示:
代码实现:
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;
}
由于每一个子树都是左小右大的,1.所以当root->key值<目标key时,应当往右找;2.当root->key值>目标key值时,应当往左找;3.当root->key值==目标key时,则说明找到了,返回true;4.若root==nullptr,说明找不到,则返回false;
②二叉搜索树的插入(可以做到自动去重、自动排序(对于中序遍历来说,中序遍历是升序))
时间复杂度:O(N)
插入的具体过程如下:
a. 树为空,则直接新增节点,赋值给root指针
b. 树不空,按二叉搜索树性质查找插入位置,插入新节点
示意图展示:
树为空,插入8 树不为空,插入0,16
效果展示:
代码实现:
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中的key值和要插入的key值相同则返回false,无法插入
//相同值,做到自动去重。
}
}
cur = new Node(key);
if (parent->_key < key)
{
parent->_right = cur;
}
else
{
parent->_left = cur;
}
return true;
}
③二叉搜索树的删除【重点!!!】
首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情况:
a. 要删除的结点无孩子结点
b. 要删除的结点只有左孩子结点
c. 要删除的结点只有右孩子结点
d. 要删除的结点有左、右孩子结点看起来有待删除节点有4种情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程如下:
情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点--直接删除
情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点--直接删除
情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点
中,再来处理该结点的删除问题--替换法删除
示意图展示:
情况一:要删除的节点无孩子节点,要注意删除节点之后将其值置空,即将其变为空指针(nullptr)或者 让原本指向该节点的指针指向空指针(nullptr),否则会出现指向野指针的问题。(这里的实现选择前者)
--删13--
情况二:删除的节点只有左孩子,删除之后要使父亲节点的该被删除节点所在的位置指向该被删除节点的左孩子。
--删1--
情况三:删除的节点只有右孩子,删除之后要使父亲节点的该被删除节点所在的位置指向该被删除节点的右孩子。
--删14--
情况四【重点!!!】:取左树最右(最大)或右树最左(最小)作为新的父亲节点,与原来的父亲节点(也是要被删除的节点)做交换,这里可以用到swap两个节点的值达到交换的效果。然后再删除那个要删除的值的节点。
--删3--
如图,选1做新父亲
如图,选4做新父亲
注意:还要考虑到极端删除8的极端情况
效果展示:
代码实现:
bool Erase(const K& key)
{
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (cur->_key < key)//root中的key值比目标key小,往右走找大。
{
parent = cur;
cur = cur->_right;
}
else if (cur->_key > key)root中的key值比目标key大,往左走找小。
{
parent = cur;
cur = cur->_left;
}
了 else//找到了要删除的节点
{
// 开始删除
//分析节点的情况
// 1、左为空//左右都为空的属于左为空和右为空中的一类,进哪一个都可以
// 2、右为空
// 3、左右都不为空
if (cur->_left == nullptr)//如果要删除的节没有左孩子
{
if (cur == _root)//就是上述删除8的那种情况,直接更新_root即可,然后
//在最后delete释放掉原来的_root(也是要删除的节点)
{
_root = cur->_right;
}
else//_root不为根节点
{
if (cur == parent->_left)//如果要删除的节点是其父亲的左孩子
{
parent->_left = cur->_right;
}
else//如果要删除的节点是其父亲的右孩子
{
parent->_right = cur->_right;
}
}
delete cur;
cur = nullptr;
}
else if (cur->_right == nullptr)//如果要删除的节没有右孩子
{
if (_root == cur)//就是上述删除8的那种情况,直接更新_root即可,然后
//在最后delete释放掉原来的_root(也是要删除的节点)
{
_root = cur->_left;
}
else//_root不为根节点
{
if (cur == parent->_left)//如果要删除的节点是其父亲的左孩子
{
parent->_left = cur->_left;
}
else//如果要删除的节点是其父亲的右孩子
{
parent->_right = cur->_left;
}
}
delete cur;
cur = nullptr;
}
else//如果要删除的节点有两个孩子
{
// 找到右子树最小节点进行替换
Node* minParent = cur;//不能minParent=nullptr;因为如果cur==_root,
//因为如果不进循环,minParent不会被初始化,则
//其为nullptr;后面的代码会报错。
Node* min = cur->_right;
while (min->_left)
{
minParent = min;
min = min->_left;
}
swap(cur->_key, min->_key);//把要删除的节点和找到的那个替代节点(左
//树最右(最大)或右树最左(最小),这里
//取右树最左(最小))
if (minParent->_left == min)//如果要删除的节点是其父亲的左节点
minParent->_left = min->_right;
else//如果要删除的节点是其父亲的右节点
minParent->_right = min->_right;
delete min;
}
return true;//删除成功,返回true;
}
}
return false;//找不到,删除失败,返回false;
}
二叉搜索树整体代码的实现(非递归):
#pragma once
#include <iostream>
using namespace std;
namespace Key
{
template<class K>
struct BSTreeNode
{
BSTreeNode<K>* _left;
BSTreeNode<K>* _right;
K _key;
BSTreeNode(const K& key)
:_left(nullptr)
, _right(nullptr)
, _key(key)
{}
};
//class BinarySearchTree
template<class K>
class BSTree
{
typedef BSTreeNode<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
{
// 开始删除
// 1、左为空
// 2、右为空
// 3、左右都不为空
if (cur->_left == nullptr)
{
if (cur == _root)
{
_root = cur->_right;
}
else
{
if (cur == parent->_left)
{
parent->_left = cur->_right;
}
else
{
parent->_right = cur->_right;
}
}
delete cur;
cur = nullptr;
}
else if (cur->_right == nullptr)
{
if (_root == cur)
{
_root = cur->_left;
}
else
{
if (cur == parent->_left)
{
parent->_left = cur->_left;
}
else
{
parent->_right = cur->_left;
}
}
delete cur;
cur = nullptr;
}
else
{
// 找到右子树最小节点进行替换
Node* minParent = cur;
Node* min = cur->_right;
while (min->_left)
{
minParent = min;
min = min->_left;
}
swap(cur->_key, min->_key);
if (minParent->_left == min)
minParent->_left = min->_right;
else
minParent->_right = min->_right;
delete min;
}
return true;
}
}
return false;
}
~BSTree()
{
_Destory(_root);
}
/*BSTree()
{}*/
// C++的用法:强制编译器生成默认的构造
BSTree() = default;
BSTree(const BSTree<K>& t)//拷贝构造
{
_root = _Copy(t._root);
}
// t2 = t1
BSTree<K>& operator=(BSTree<K> t)
{
swap(_root, t._root);
return *this;
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
private:
Node* _Copy(Node* root)
{
if (root == nullptr)
{
return nullptr;
}
Node* copyRoot = new Node(root->_key);
copyRoot->_left = _Copy(root->_left);
copyRoot->_right = _Copy(root->_right);
return copyRoot;
}
void _Destory(Node*& root)
{
if (root == nullptr)
{
return;
}
_Destory(root->_left);
_Destory(root->_right);
delete root;
root = nullptr;
}
void _InOrder(Node* root)
{
if (root == nullptr)
{
return;
}
_InOrder(root->_left);
cout << root->_key << " ";
_InOrder(root->_right);
}
private:
Node* _root = nullptr;
};
3.二叉搜索树的操作功能及其实现(递归版本)
这里函数要分开写的原因:
要分开写的原因是,如FindR函数需要两个参数,一个是root当前根,一个是key,但Find在外调用函数时,又无法将私有成员变量root传给FindR,所以无法完成递归,因为参数不够。所以只能通过间接调用的方式,来获取成员变量root给_FindR,完成递归。
①. 二叉搜索树的查找
a、从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。
b、最多查找高度次,走到到空,还没找到,这个值不存在
代码实现:
public:
bool FindR(const K& key)
{
return _FindR(_root, key);//要分开写的原因是,Find函数需要两个参数,一个是root当前
//根,一个是key,但Find在外调用函数时,又无法将私有成员变
//量root传给FindR,所以无法完成递归,因为参数不够。所以只
//能通过间接调用的方式,来获取成员变量root给_FindR,完成
//递归
}
private:
bool _FindR(Node* root, const K& key)
{
if (root == nullptr)
return false;
if (root->_key < key)
return _FindR(root->_right, key);
else if (root->_key > key)
return _FindR(root->_left, key);
else
return true;
}
②二叉搜索树的插入(可以做到自动去重、自动排序(对于中序遍历来说,中序遍历是升序))
插入的具体过程如下:
a. 树为空,则直接新增节点,赋值给root指针
b. 树不空,按二叉搜索树性质查找插入位置,插入新节点
public:
bool InsertR(const K& key)
{
return _InsertR(_root, key);
}
private:
bool _InsertR(Node*& root, const K& key)
{
if (root == nullptr)
{
root = new Node(key);
return true;
}
if (root->_key < key)
return _InsertR(root->_right, key);
else if (root->_key > key)
return _InsertR(root->_left, key);
else
return false;
}
③二叉搜索树的删除【重点!!!】
这里传的Node*&---- (引用)是点睛之笔,这里的引用配合上了递归,省去了判断删除的节点到底是其父亲的左子树还是右子树的判断,简化了过程。
public:
bool EraseR(const K& key)//因为如果
{
return _EraseR(_root, key);
}
private:
bool _EraseR(Node*& root, const K& key)
{
if (root == nullptr)//找不到,返回false
return false;
if (root->_key < key)//root中的key值比目标key小,往右走
return _EraseR(root->_right, key);
else if (root->_key > key)//root中key值比目标key大,往左走
return _EraseR(root->_left, key);
else//root中key值和目标key值相同,开始执行删除的逻辑
{
Node* del = root;
if (root->_left == nullptr)
{
root = root->_right;
}
else if (root->_right == nullptr)
{
root = root->_left;
}
else
{
// 找右树的最左节点替换删除
Node* min = root->_right;
while (min->_left)
{
min = min->_left;
}
swap(root->_key, min->_key);
//return EraseR(key);
//错的,因为交换之后从根开始遍历已经不是二叉搜索树了
return _EraseR(root->_right, key);//但该右子树仍是二叉搜索树
}
delete del;
return true;
}
}
二叉搜索树整体代码实现(递归版本):
#pragma once
#include <iostream>
using namespace std;
namespace Key
{
template<class K>
struct BSTreeNode
{
BSTreeNode<K>* _left;
BSTreeNode<K>* _right;
K _key;
BSTreeNode(const K& key)
:_left(nullptr)
, _right(nullptr)
, _key(key)
{}
};
//class BinarySearchTree
template<class K>
class BSTree
{
typedef BSTreeNode<K> Node;
public:
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);
}
~BSTree()
{
_Destory(_root);
}
/*BSTree()
{}*/
// C++的用法:强制编译器生成默认的构造
BSTree() = default;
BSTree(const BSTree<K>& t)
{
_root = _Copy(t._root);
}
// t2 = t1
BSTree<K>& operator=(BSTree<K> t)
{
swap(_root, t._root);
return *this;
}
private:
Node* _Copy(Node* root)
{
if (root == nullptr)
{
return nullptr;
}
Node* copyRoot = new Node(root->_key);
copyRoot->_left = _Copy(root->_left);
copyRoot->_right = _Copy(root->_right);
return copyRoot;
}
void _Destory(Node*& root)
{
if (root == nullptr)
{
return;
}
_Destory(root->_left);
_Destory(root->_right);
delete root;
root = nullptr;
}
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->_left == nullptr)
{
root = root->_right;
}
else if (root->_right == nullptr)
{
root = root->_left;
}
else
{
// 找右树的最左节点替换删除
Node* min = root->_right;
while (min->_left)
{
min = min->_left;
}
swap(root->_key, min->_key);
//return EraseR(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;
}
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;
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);
}
private:
Node* _root = nullptr;
};
4.二叉搜索树四大函数的实现
①.构造函数
注意:拷贝构造也是构造函数,有了拷贝构造之后,如果不写构造函数的话,编译器不能再自动生成默认的无参构造函数了,在运行时会报错:无默认构造函数。因为可能这个对象是需要单独建立的,不一定是由另一个拷贝构造而来的。所以我们需要自己写一个构造函数。但该构造函数并不一定需要我们实现的,因为默认的无参构造函数即可,这时,C++中有一个用法是 BSTree()=default;的方法,意思是强制编译器自动生成默认构造函数
public:
// C++的用法:强制编译器生成默认的构造
BSTree() = default;
②.析构函数
public:
~BSTree()
{
_Destory(_root);
}
private:
void _Destory(Node*& root)
{
if (root == nullptr)
{
return;
}
_Destory(root->_left);
_Destory(root->_right);
delete root;
root = nullptr;
}
③.拷贝构造函数
这里采用了前序遍历的方式的拷贝构造,遇到一个建一个,然后再递归到左右孩子重复此动作。
public:
BSTree(const BSTree<K>& t)//拷贝构造
{
_root = _Copy(t._root);
}
private:
Node* _Copy(Node* root)
{
if (root == nullptr)
{
return nullptr;
}
Node* copyRoot = new Node(root->_key);
copyRoot->_left = _Copy(root->_left);
copyRoot->_right = _Copy(root->_right);
return copyRoot;
}
④.赋值运算符重载
(只能定义在类内,在外类没有意义,也实现不了,因为没有this指针,无法对*this对象进行赋值)
// t2 = t1
BSTree<K>& operator=(BSTree<K> t)
{
swap(_root, t._root);
return *this;
}
5.二叉搜索树的应用
①K模型(搜索-判断有无):
K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值。
比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:
·以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树
·在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误
以上实现的Find和FindR就是K模型。
②.KV模型(由K模型改写而来。每个key对应一个value,存的是一个个键值对,找到对应的key,对其value进行操作):
每一个关键码key,都有与之对应的值Value,即<Key, Value>的键值对。该种方式在现实生活中非常常见:
·比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英
文单词与其对应的中文<word, chinese>就构成一种键值对;
·再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出
现次数就是<word, count>就构成一种键值对
效果展示图:
代码实现:
(本质就是在struct BSTreeNode中增加一个 V _value;值。与key一一对应形成键值对)
namespace KeyValue
{
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)
:_left(nullptr)
, _right(nullptr)
, _key(key)
, _value(value)
{}
};
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;
}
bool Erase(const K& key)
{
//...
return true;
}
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 = nullptr;
};
void TestBSTree1()
{
BSTree<string, string> dict;
dict.Insert("sort", "排序");
dict.Insert("left", "左边");
dict.Insert("right", "右边");
dict.Insert("string", "字符串");
dict.Insert("insert", "插入");
string str;
while (cin >> str)
{
BSTreeNode<string, string>* ret = dict.Find(str);
if (ret)
{
cout << "对应的中文:" << ret->_value << endl;
}
else
{
cout << "对应的中文->无此单词" << endl;
}
}
}
void TestBSTree2()
{
string arr[] = { "香蕉", "苹果", "香蕉", "草莓", "香蕉", "苹果", "苹果", "苹果" };
BSTree<string, int> countTree;
for (auto& str : arr)
{
//BSTreeNode<string, int>* ret = countTree.Find(str);
auto ret = countTree.Find(str);
if (ret)
{
ret->_value++;
}
else
{
countTree.Insert(str, 1);
}
}
countTree.InOrder();
}
}
6.二叉搜索树树性能分析
插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二
叉搜索树的深度的函数,即结点越深,则比较次数越多。
但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:
最优情况下(接近满二叉树)
二叉搜索树为完全二叉树(或者接近完全二叉树),其平均比较次数为:
log(N)=h=高度次
最差情况下(接近单枝/边树)
二叉搜索树退化为单支树(或者类似单支),其平均比较次数为:
N次
问题:
如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插
入关键码,二叉搜索树的性能都能达到最优?那AVL和红黑树就要上场了。敬请期待,后续更新。
二、 二叉树进阶面试题
1.链表部分(二叉搜索树方法)
①.找链表交点
思路:KV模型,value存较长的那条链表的所有节点的地址,然后遍历另一条链表节点的地址,分别与KV树中的所有节点的值比较,暴力遍历比较。
②.复杂链表的复制
思路:KV模型,key里存的是原来的节点,value存的是拷贝的节点。因为值键对的存在,可以让key映射value,使得拷贝节点能根据原来的节点(也就是key)来映射拷贝的节点(value)
2.二叉树部分
①.根据二叉树创建字符串
string tree2str(TreeNode* root) {
if (root == nullptr)
return string();
string 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;
}
②二叉树的层析遍历(顺序)
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
int Levelsize = 0;
if (root != nullptr)
{
q.push(root);
Levelsize = 1;
}
vector<vector<int>> v;
while (!q.empty())
{
int i = 0;
vector<int> vv;
for (i = 0; i < Levelsize; i++)//一层一层去
{
TreeNode* Front = q.front();
if (Front->left)
q.push(Front->left);
if (Front->right)
q.push(Front->right);
vv.push_back(Front->val);
q.pop();
}
v.push_back(vv);
Levelsize = q.size(); //更新一层的个数
}
return v;
}
③.二叉树的层析遍历(逆序)
只需要将顺序遍历的reverse翻转一下即可
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*> q;
int Levelsize = 0;
if (root != nullptr)
{
q.push(root);
Levelsize = 1;
}
vector<vector<int>> v;
while (!q.empty())
{
int i = 0;
vector<int> vv;
for (i = 0; i < Levelsize; i++)//一层一层去
{
TreeNode* Front = q.front();
if (Front->left)
q.push(Front->left);
if (Front->right)
q.push(Front->right);
vv.push_back(Front->val);
q.pop();
}
v.push_back(vv);
Levelsize = q.size(); //更新一层的个数
}
reverse(v.begin(), v.end());
return v;
}
④.二叉树的最近公共祖先
法1.
算法:dfs深度优先遍历
思路:左右两个节点分别在左右子树,则当前节点是最近公共祖先节点
bool find(TreeNode* root, TreeNode* k)
{
if (root == nullptr)
return false;
if (root == k)
return true;
return find(root->left, k) || find(root->right, k);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == q || root == p)
return root;
bool pFindL, pFindR, qFindL, qFindR;
pFindL = find(root->left, p);
pFindR = !pFindL;
qFindL = find(root->left, q);
qFindR = !qFindL;
if (pFindL && qFindR || pFindR && qFindL)
return root;
else if (pFindL && qFindL)
return lowestCommonAncestor(root->left, p, q);
else if (pFindR && qFindR)
return lowestCommonAncestor(root->right, p, q);
//两边都不在
return nullptr;
}
法2.
数据结构:栈-用于求路径 链表-用路径把二叉树问题变成链表相交问题
算法:杂类算法-快慢指针
思路:用栈,转化成链表相交问题
bool FindPath(TreeNode* root, TreeNode* x, stack<TreeNode*>& path)//路径存到栈中
{
if (root == nullptr)//若是空的直接返回false;
{
return false;
}
path.push(root);
if (root == x)//是则插入后直接返回true;
{
return true;
}
if (!(FindPath(root->left, x, path) || FindPath(root->right, x, path)))//不是则判断两边是否有,若没有则pop()当前这个,有则保留当前这个
{
path.pop();
return false;
}
return true;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
stack<TreeNode*> pPath, qPath;
FindPath(root, p, pPath);
FindPath(root, q, qPath);
while (!(pPath.empty()) && !(qPath.empty()))
{
if (pPath.size() > qPath.size())
pPath.pop();
else if (pPath.size() < qPath.size())
qPath.pop();
else if (pPath.size() == qPath.size())
{
if (pPath.top() == qPath.top())
return pPath.top();
else
{
pPath.pop();
qPath.pop();
}
}
}
return nullptr;//没有交点
}
⑤. 二叉搜索树与双向链表
算法:双指针/前后指针 法
思路:由于题目要求排成升序的,且是二叉搜索树,所以要用中序遍历。二叉树的问题都要分成
中 左子树 右子树 这三块构成一个整体来看,左右子树细节忽略。关键点:而且注意!!!prev要用引用
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) {
TreeNode* prev = nullptr;
InOrderConvert(pRootOfTree, prev);
//转化完之后,找到链表的起点
TreeNode* head = pRootOfTree;
while (head && head->left)//head: 确保head一开始进去不是nullptr
{
head = head->left;
}
return head;
}
⑥.从前序遍历与中序遍历序列构建二叉树
法1.推荐这种
TreeNode* _buildTree(vector<int> preorder, vector<int> inorder, int& prei, int inbegin, int inend)
{
if (inbegin > inend)
return nullptr;
if (prei >= preorder.size())//这种题一般前序和中序都是正确的,不需要判断
return nullptr;
TreeNode* root = new TreeNode;
root->val = preorder[prei++];
int ini = inbegin;
while (ini <= inend)
{
if (inorder[ini] == root->val)
break;
ini++;
}
//在inorder中找到preorder中对应的根节点inroot
//找区间
//[0,inroot) inroot [inroot+1,inorder.size())
root->left = _buildTree(preorder, inorder, prei, inbegin, ini - 1);
root->right = _buildTree(preorder, inorder, prei, ini + 1, inend);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
//从前序遍历中找根节点,将中序遍历进行切割
int prei = 0;
TreeNode* root = _buildTree(preorder, inorder, prei, 0, inorder.size() - 1);
return root;
}
法2.
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0)
return nullptr;
int val = preorder[0];
TreeNode* root = new TreeNode(val);
if (preorder.size() == 1)
{
return root;
}
//找根节点
int index = 0;
for (index = 0; index < inorder.size(); index++)
{
if (inorder[index] == val)
break;
}
//分割出左右子树的中序遍历
vector<int> leftinorder(inorder.begin(), inorder.begin() + index);
vector<int> rightinorder(inorder.begin() + index + 1, inorder.end());
//分割出左右子树的前序遍历
vector<int> leftpreorder(preorder.begin() + 1, preorder.begin() + 1 + leftinorder.size());
vector<int> rightpreorder(preorder.begin() + leftinorder.size() + 1, preorder.end());
//继续深度递归
root->left = buildTree(leftpreorder, leftinorder);
root->right = buildTree(rightpreorder, rightinorder);
return root;
}