1、二叉树理论基础
1.1、二叉树的种类
我们在解题过程中,二叉树有两种主要的形式:满二叉树和完全二叉树。
1.1.1、满二叉树
满二叉树:如果一棵二叉树只有度为0的节点和度为2的节点,并且度为0的节点在同一层上,则这棵二叉树为满二叉树。
如图所示:
这棵二叉树为满二叉树,也可以说是深度为k,有 2^k - 1 个节点的二叉树。
1.1.2、完全二叉树
什么是完全二叉树?
完全二叉树的定义如下:在完全二叉树中,除了最底层的节点可能没有填满,其余每层节点数都达到最大值,并且最下面一层的节点都集中在最左边的若干位置。若最底层为第 k 层,则该层包含 1~2^(k - 1) 个节点
大家要看完全二叉树的定义,不要对完全二叉树的判断迷迷瞪瞪。
举个典型的例子:
之前我们刚刚讲过优先级队列其实是一个堆,堆就是一棵完全二叉树,同时保证父子节点的顺序关系。
1.1.3、二叉搜索树
前面介绍的树都是没有数值的,而二叉搜索数是有数值的,二叉搜索树是一棵有序树
- 若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
- 若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
- 它的左、右子树也分别为二叉排序树
下面这两棵树都是搜索树
1.1.4、平衡二叉搜索树
顾名思义,平衡二叉搜索树是在二叉搜索树的基础上平衡了左右子树高度。
平衡二叉搜索树:又被称为 AVL(Adelson-Velsky and Landis)数,且具有以下性质:它是一棵空树或他的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
如图:
最后一棵不是平衡二叉树,因为它的左右两个子树的高度差的绝对值超过了1。
C++中map、set、multimap、multiset 的低层实现都是平衡二叉搜索树,所以map、set的增删操作时间复杂度是 logn,注意,unordered_map 和 unordered_set 的低层实现是哈希表,增删操作时间复杂度是 O(1)。
所以大家使用自己熟悉的编程语言写算法,一定要知道常用的容器低层都是如何实现的,最基本的就是map、set等等,否则自己写的代码,自己对其性能分析都分析不清楚!
1.2、二叉树的存储方式
二叉树可以是链式存储,也可以是顺序存储。
那么链式存储方式就用指针, 顺序存储的方式就是用数组。
顾名思义就是顺序存储的元素在内存是连续分布的,而链式存储则是通过指针把分布在散落在各个地址的节点串联一起。
链式存储如图:
链式存储是大家很熟悉的一种方式,那么我们来看看如何顺序存储呢?
其实就是用数组来存储二叉树,顺序存储的方式如图:
用数组来存储二叉树如何遍历的呢?
如果父节点的数组下标是 i,那么它的左孩子就是 i 2 + 1,右孩子就是 i 2 + 2。
但是用链式表示的二叉树,更有利于我们理解,所以一般我们都是用链式存储二叉树。
所以大家要了解,用数组依然可以表示二叉树。
1.3、二叉树的遍历方式
关于二叉树的遍历方式,要知道二叉树遍历的基本方式都有哪些。
一些同学用做了很多二叉树的题目了,可能知道前中后序遍历,可能知道层序遍历,但是却没有框架。
我这里把二叉树的几种遍历方式列出来,大家就可以一一串起来了。
二叉树主要有两种遍历方式:
- 深度优先遍历:先往深走,遇到叶子节点再往回走。
- 广度优先遍历:一层一层的去遍历。
这两种遍历是图论中最基本的两种遍历方式,后面在介绍图论的时候 还会介绍到。
那么从深度优先遍历和广度优先遍历进一步拓展,才有如下遍历方式:
- 深度优先遍历
- 前序遍历(递归法,迭代法)
- 中序遍历(递归法,迭代法)
- 后序遍历(递归法,迭代法)
- 广度优先遍历
- 层次遍历(迭代法)
在深度优先遍历中:有三个顺序,前中后序遍历, 有同学总分不清这三个顺序,经常搞混,我这里教大家一个技巧。
这里前中后,其实指的就是中间节点的遍历顺序,只要大家记住 前中后序指的就是中间节点的位置就可以了。
看如下中间节点的顺序,就可以发现,中间节点的顺序就是所谓的遍历方式
- 前序遍历:中左右
- 中序遍历:左中右
- 后序遍历:左右中
大家可以对着如下图,看看自己理解的前后中序有没有问题。
最后再说一说二叉树中深度优先和广度优先遍历实现方式,我们做二叉树相关题目,经常会使用递归的方式来实现深度优先遍历,也就是实现前中后序遍历,使用递归是比较方便的。
之前我们讲栈与队列的时候,就说过栈其实就是递归的一种是实现结构,也就说前中后序遍历的逻辑其实都是可以借助栈使用非递归的方式来实现的。
而广度优先遍历的实现一般使用队列来实现,这也是队列先进先出的特点所决定的,因为需要先进先出的结构,才能一层一层的来遍历二叉树。
这里其实我们又了解了栈与队列的一个应用场景了。
具体的实现我们后面都会讲的,这里大家先要清楚这些理论基础。
1.4、二叉树的定义
刚刚我们说过了二叉树有两种存储方式顺序存储,和链式存储,顺序存储就是用数组来存,这个定义没啥可说的,我们来看看链式存储的二叉树节点的定义方式。
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子.
这里要提醒大家要注意二叉树节点定义的书写方式。
在现场面试的时候 面试官可能要求手写代码,所以数据结构的定义以及简单逻辑的代码一定要锻炼白纸写出来。
因为我们在刷leetcode的时候,节点的定义默认都定义好了,真到面试的时候,需要自己写节点定义的时候,有时候会一脸懵逼!
2、二叉树的递归遍历
144. 二叉树的前序遍历 - 力扣(LeetCode)
94. 二叉树的中序遍历 - 力扣(LeetCode)
145. 二叉树的后序遍历 - 力扣(LeetCode)
这次我们要好好谈一谈递归,为什么很多同学看递归算法都是“一看就会,一写就废”。
主要是对递归不成体系,没有方法论,每次写递归算法 ,都是靠玄学来写代码,代码能不能编过都靠运气。
本篇将介绍前后中序的递归写法,一些同学可能会感觉很简单,其实不然,我们要通过简单题目把方法论确定下来,有了方法论,后面才能应付复杂的递归。
这里帮助大家确定下来递归算法的三个要素。每次写递归,都按照这三要素来写,可以保证大家写出正确的递归算法!
- 确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。
- 确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
- 确定单层递归的逻辑: 确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。
好了,我们确认了递归的三要素,接下来就来练练手:
以下以前序遍历为例:
确定递归函数的参数和返回值:因为要打印出前序遍历节点的数值,所以参数里需要传入vector在放节点的数值,除了这一点就不需要在处理什么数据了也不需要有返回值,所以递归函数返回类型就是void,代码如下:
void traversal(TreeNode* cur, vector<int>& vec)
确定终止条件:在递归的过程中,如何算是递归结束了呢,当然是当前遍历的节点是空了,那么本层递归就要要结束了,所以如果当前遍历的这个节点是空,就直接return,代码如下:
if (cur == nullptr) return;
确定单层递归的逻辑:前序遍历是中左右的循序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下:
vec.push_back(cur->val); // 中
traversal(cur->left, vec); // 左
traversal(cur->right, vec); // 右
完整代码:
class Solution{
public:
// 前序遍历
void traversal(TreeNode* cur, vector<int>& vec){
if(cur == nullptr) return;
vec.push_back(cur->val); // 中
traversal(cur->left, vec); // 左
traversal(cur->right, vec); // 右
}
vector<int> preorderTraversal(TreeNode* root){
vector<int> vec;
traversal(root, vec);
return vec;
}
};
中序遍历和后序遍历其实都是大同小异的。
3、二叉树的迭代遍历
看完本篇大家可以使用迭代法,再重新解决如下三道leetcode上的题目:
- 144.二叉树的前序遍历
- 94.二叉树的中序遍历
- 145.二叉树的后序遍历
为什么可以用迭代法(非递归的方式)来实现二叉树的前后中序遍历呢?
我们在栈与队列:匹配问题都是栈的强项(opens new window)中提到了,递归的实现就是:每一次递归调用都会把函数的局部变量、参数值和返回地址等压入调用栈中,然后递归返回的时候,从栈顶弹出上一次递归的各项参数,所以这就是递归为什么可以返回上一层位置的原因。
此时大家应该知道我们用栈也可以是实现二叉树的前后中序遍历了。
3.1、前序遍历(迭代法)
我们先看一下前序遍历。
前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。
为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。
动画如下:
不难写出如下代码:(注意空节点不入栈)
/**
* 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*> stk;
vector<int> result;
if(root == nullptr){
return result;
}
stk.push(root); // 先将根节点入栈
while(!stk.empty()){
TreeNode* node = stk.top(); // 中
result.push_back(node->val);
stk.pop();
if(node->right){ // 右(空节点不入栈)
stk.push(node->right);
}
if(node->left){ // 左(空节点不入栈)
stk.push(node->left);
}
}
return result;
}
};
此时会发现貌似使用迭代法写出前序遍历并不难,确实不难。
此时是不是想改一点前序遍历代码顺序就把中序遍历搞出来了?
其实还真不行!
但接下来,再用迭代法写中序遍历的时候,会发现套路又不一样了,目前的前序遍历的逻辑无法直接应用到中序遍历上。
3.2、中序遍历(迭代法)
为了解释清楚,我说明一下 刚刚在迭代的过程中,其实我们有两个操作:
- 处理:将元素放进result数组中
- 访问:遍历节点
分析一下为什么刚刚写的前序遍历的代码,不能和中序遍历通用呢,因为前序遍历的顺序是中左右,先访问的元素是中间节点,要处理的元素也是中间节点,所以刚刚才能写出相对简洁的代码,因为要访问的元素和要处理的元素顺序是一致的,都是中间节点。
那么再看看中序遍历,中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树左面的最底部,再开始处理节点(也就是在把节点的数值放进result数组中),这就造成了处理顺序和访问顺序是不一致的。
那么在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
动画如下:
中序遍历C++代码
/**
* 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) {
stack<TreeNode*> stk;
vector<int> result;
TreeNode* cur = root;
while(cur || !stk.empty()){
if(cur != nullptr){ // 用指针来访问节点,访问到最底层
stk.push(cur); // 将访问过的节点放入栈中
cur = cur->left;
}
else{
cur = stk.top(); // 从栈里弹出的数据,就是要处理的数据
stk.pop();
result.push_back(cur->val);
cur = cur->right;
}
}
return result;
}
};
3.3、后序遍历(迭代法)
再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了,如下图:
所以后序遍历只需要前序遍历的代码稍作修改就可以了,代码如下:
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root){
vector<int> result;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* cur = st.top(); // 中
result.push_back(cur->val);
st.pop();
if(cur->left) st.push(cur->left); // 左
if(cur->right) st.push(cur->right); // 右
}
reverse(result.begin(), result.end()); // 中右左 --> 左右中
return result;
}
};
4、二叉树的统一迭代法
此时我们在二叉树:一入递归深似海,从此offer是路人(opens new window)中用递归的方式,实现了二叉树前中后序的遍历。
在二叉树:听说递归能做的,栈也能做!(opens new window)中用栈实现了二叉树前后中序的迭代遍历(非递归)。
之后我们发现迭代法实现的先中后序,其实风格也不是那么统一,除了先序和后序,有关联,中序完全就是另一个风格了,一会用栈遍历,一会又用指针来遍历。
实践过的同学,也会发现使用迭代法实现先中后序遍历,很难写出统一的代码,不像是递归法,实现了其中的一种遍历方式,其他两种只要稍稍改一下节点顺序就可以了。
其实针对三种遍历方式,使用迭代法是可以写出统一风格的代码!
重头戏来了,接下来介绍一下统一写法。
我们以中序遍历为例,在二叉树:听说递归能做的,栈也能做!(opens new window)中提到说使用栈的话,无法同时解决访问节点(遍历节点)和处理节点(将元素放进结果集)不一致的情况。
那我们就将访问的节点放入栈中,把要处理的节点也放入栈中但是要做标记。
如何标记呢,就是要处理的节点放入栈之后,紧接着放入一个空指针作为标记。 这种方法也可以叫做标记法。
二叉树前序遍历、中序遍历、后序遍历的统一风格的代码
前序遍历
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root){
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) return result;
st.push(root); // 根节点先入栈
while(!st.empty()){
TreeNode* node = st.top();
if(node != NULL){ // 如果节点非空,表明当前节点不是我们设置标志的节点,我们需要继续判断当前节点是否有左右孩子
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
if(node->right) st.push(node->right); // 右(空节点不入栈)
if(node->left) st.push(node->left); // 左(空节点不入栈)
st.push(node); // 中
st.push(NULL); // 给当前节点设置标志
}
else{
st.pop(); // 弹出空指针(即我们设置的标志)
result.push_back(st.top()); // 这是我们想要操作的节点
st.pop();
}
}
return result;
}
};
中序遍历
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root){
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) return result;
st.push(root); // 根节点先入栈
while(!st.empty()){
TreeNode* node = st.top();
if(node != NULL){ // 如果节点非空,表明当前节点不是我们设置标志的节点,我们需要继续判断当前节点是否有左右孩子
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
if(node->right) st.push(node->right); // 右(空节点不入栈)
st.push(node); // 中
st.push(NULL); // 给当前节点设置标志
if(node->left) st.push(node->left); // 左(空节点不入栈)
}
else{
st.pop(); // 弹出空指针(即我们设置的标志)
result.push_back(st.top()); // 这是我们想要操作的节点
st.pop();
}
}
return result;
}
};
后序遍历
class Solution{
public:
vector<int> postorderTraversal(TreeNode* root){
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) return result;
st.push(root); // 根节点先入栈
while(!st.empty()){
TreeNode* node = st.top();
if(node != NULL){ // 如果节点非空,表明当前节点不是我们设置标志的节点,我们需要继续判断当前节点是否有左右孩子
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
st.push(node); // 中
st.push(NULL); // 给当前节点设置标志
if(node->right) st.push(node->right); // 右(空节点不入栈)
if(node->left) st.push(node->left); // 左(空节点不入栈)
}
else{
st.pop(); // 弹出空指针(即我们设置的标志)
result.push_back(st.top()); // 这是我们想要操作的节点
st.pop();
}
}
return result;
}
};
此时我们写出了统一风格的迭代法,不用在纠结于前序写出来了,中序写不出来的情况了。
但是统一风格的迭代法并不好理解,而且想在面试直接写出来还有难度的。
所以大家根据自己的个人喜好,对于二叉树的前中后序遍历,选择一种自己容易理解的递归和迭代法。
5、二叉树的层序遍历
层序遍历一个二叉树,就收从左到右一层一层的去遍历二叉树。这种遍历方式和我们之前将的都不太一样。
需要借用一个辅助数据结构即队列来实现,队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。
而这种层序遍历方式就是图论中的广度优先遍历,只不过我们应用在二叉树上。
使用队列实现二叉树广度优先遍历,动画如下:
这样就实现了层序从左到右遍历二叉树。
5.1、二叉树的层序遍历
我们用层序遍历的方法,实现了二叉树的广度搜索问题。C++代码如下:
/**
* 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<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> que;
if(root == NULL) return result;
que.push(root);
while(!que.empty()){
vector<int> temp; // 用一个临时的一维数组来存二叉树中一层的节点
int size = que.size(); // 队列的大小,即二叉树当前这一层的节点数
while(size--){ // 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
TreeNode* cur = que.front();
temp.push_back(cur->val);
que.pop();
if(cur->left) que.push(cur->left); // 左节点非空就入队
if(cur->right) que.push(cur->right); // 右节点非空就入队
}
result.push_back(temp);
}
return result;
}
};
5.2、二叉树的层序遍历 II
107. 二叉树的层序遍历 II - 力扣(LeetCode)
这道题的思路很简单,就是先按照顺序自上而下的层序遍历二叉树,然后在最后面要输出结构的时候,我们反转一下二维数组的顺序就行了。
C++代码如下:
/**
* 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<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> que;
if(root == nullptr) return result;
que.push(root);
while(!que.empty()){
int size = que.size();
vector<int> temp;
while(size--){
TreeNode* cur = que.front();
temp.push_back(cur->val);
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
result.push_back(temp);
}
reverse(result.begin(), result.end()); // 在这里反转以下数组即可
return result;
}
};
5.3、二叉树的右视图
思路:
层序遍历的时候,判断是否遍历到单层的最后面的元素,如果是,就放进result数组,随后返回result就可以了。
/**
* 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> rightSideView(TreeNode* root) {
vector<int> result;
queue<TreeNode*> que;
if(root == nullptr) return result;
que.push(root);
// result.push_back(root->val); // 根节点只有一个,肯定能被右侧看到
while(!que.empty()){
int size = que.size(); // 当前这一层的节点数
while(size){
TreeNode* cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
if(size == 1){ // 如果size为1,说明当前访问的节点是这一层的最后一个节点
result.push_back(cur->val);
}
size--;
}
}
return result;
}
};
5.4、二叉树的层平均值
本题就是层序遍历的时候,把单层求个总和再取一个均值。
/**
* 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<double> averageOfLevels(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<double> result;
while (!que.empty()) {
int size = que.size();
double sum = 0; // 统计每一层的和
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
sum += node->val;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(sum / size); // 将每一层均值放进结果集
}
return result;
}
};
5.5、N 叉树的层序遍历
思路:
这道题依旧是模板提题,只不过是一个节点有多个孩子了,需要注意一下N叉树的定义方式。
C++代码:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> result;
queue<Node*> que;
if(root != NULL) que.push(root);
while(!que.empty()){
int size = que.size();
vector<int> temp;
for(int i = 0; i < size; i++){
Node* cur = que.front();
temp.push_back(cur->val); // 就算N叉树的每组子节点都用null来分隔,我们在后面节点入队的时候也有判断
que.pop();
for(int j = 0; j < cur->children.size(); j++){
if(cur->children[j]){ // 在这里判断
que.push(cur->children[j]);
}
}
}
result.push_back(temp);
}
return result;
}
};
5.6、在每个树行中找最大值
515. 在每个树行中找到最大值 - 力扣(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> largestValues(TreeNode* root) {
vector<int> result;
queue<TreeNode*> que;
if(root == nullptr) return result;
que.push(root);
while(!que.empty()){
int size = que.size();
int max = INT_MIN; // 初始化为最小值
for(int i = 0; i < size; i++){
TreeNode* cur = que.front();
if(cur->val > max){
max = cur->val;
}
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
result.push_back(max);
}
return result;
}
};
5.7、填充每个节点的下一个右侧节点指针
116. 填充每个节点的下一个右侧节点指针 - 力扣(LeetCode)
思路:
本题依旧是层序遍历,只不过在单层遍历的时候,让左边的节点指向右边的节点,然后让单层中最后一个节点指向NULL就行了。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> que;
if(root == NULL) return root;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){
Node* cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
cur->next = que.front(); // 左孩子指向右孩子
if(i == size - 1){ // 如果当前节点是单层中最后一个节点,那我们让它指向NULL
cur->next = NULL;
}
}
}
return root;
}
};
5.8、填充每个节点的下一个右侧节点 II
思路:
跟那道题的不同之处,是上面这道题题目说的是一棵完全二叉树,这道题没有这么要求。但其实思路是一样的,一样的代码迁移过来。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> que;
if(root == NULL) return root;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){
Node* cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
cur->next = que.front(); // 左边的节点指向它右边的节点
if(i == size - 1){ // 如果当前节点是单层中最后一个节点,那么让它指向NULL
cur->next = NULL;
}
}
}
return root;
}
};
5.9、二叉树的最大深度
思路:
如果使用迭代法的话,使用二叉树的层序遍历是最合适的,因为二叉树的层数就是它的深度,因为我们至少要遍历一遍二叉树,才能知道它的深度,层序遍历时间复杂度也是O(n),所以这道题的迭代法依旧是层序遍历的模板题,套入模板就行了。
/**
* 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:
int maxDepth(TreeNode* root) {
int depth = 0; // 二叉树的深度
queue<TreeNode*> que;
if(root == NULL) return 0;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){ // 遍历单层二叉树的节点
TreeNode* cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
depth++; // 深度加1
}
return depth;
}
};
5.10、二叉树的最小深度
相对于104. 二叉树的最大深度,本题也还可以使用层序遍历的方式来解决,思路是一样的。
需要注意的是,只有当左右孩子都为空的时候,才说明遍历的节点是最低的叶子节点。如果其中一个孩子不为空,则不是最低点。
/**
* 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:
int minDepth(TreeNode* root) {
int minDepth = 0; // 记录二叉树的最小深度
queue<TreeNode*> que;
if(root == nullptr) return 0;
que.push(root);
minDepth++;
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){
TreeNode* cur = que.front();
que.pop();
if(!cur->left && !cur->right){ // 只有当叶子节点的左右孩子都为空,说明改叶子节点是最低点
return minDepth;
}
else{
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
minDepth++;
}
return minDepth;
}
};
5.11、总结
二叉树的层序遍历,就是图论中广度优先搜索在二叉树的应用,需要借助队列来实现(此时又发现队列的另一个应用了,慢慢积累吧!)
十道题我分了两天写!其实也不算两天,花的时间不多,每一道题都是自己写的再去看代码随想录,发现自己写的跟随想录几乎是一样的。这应该算是一点点小进步吧!希望有一天能写出比随想录更优的代码出来。
6、翻转二叉树
6.1、迭代法
思路:
迭代法:这是我比较擅长的
/**
* 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* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if(root == nullptr) return root;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){
TreeNode* cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
if(cur->left || cur->right){ // 如果当前节点存在左或者是右叶子节点,才需要翻转
TreeNode* temp = cur->left;
cur->left = cur->right; // 左孩子节点指向右孩子节点
cur->right = temp; // 右孩子节点指向左孩子节点
}
}
}
return root;
}
};
6.2、递归法
这道题目是非常经典的题目,也是比较简单的题目(至少一看就会)。但正是因为这道题太简单,一看就会,导致很多同学没有抓到本质,稀里糊涂的就把这道题目过了(我就是!!)。这道题的重点应该放在递归法上,而不是迭代法,因为迭代法太简单了。
要翻转一棵二叉树,其实就是把它的当前节点的左右节点交换一下就可以了。
关键在于遍历顺序,前中后应该选择哪一种?(我虽然做对了,但是我根本就没有考虑遍历的顺序)。
注意,遍历的过程去翻转每一个节点的左右孩子就能达到整体翻转的效果
这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历会把某些节点的左右孩子翻转两次!建议拿纸画一画,就理解了。
那么层序遍历可不可以呢?当然可以,我前面迭代法用的就是层序遍历。
递归法C++代码:
/**
* 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:
// 迭代法(已解) || 递归法(已解)
/*
void recursion(TreeNode* node){ // 这是我的解法,写的比较外行
if(node == nullptr) return;
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
recursion(node->left);
recursion(node->right);
}
TreeNode* invertTree(TreeNode* root) {
TreeNode* node = root;
recursion(node);
return root;
}
*/
// 代码随想录的解法,其实大同小异,但是其中的思想相差甚远
// 前序、后序的方法都可以,唯独中序不行,中序会将一些节点翻转两次!!!
TreeNode* invertTree(TreeNode* root){
if(root == nullptr) return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
7、二叉树周末总结
代码随想录 - 二叉树 - 7、二叉树周末总结,这里总结的很好了。
8、对称二叉树
今天是除夕夜的前一天,感觉好累,这道题的解法思路就去看代码随想录里的题解吧
代码随想录 - 二叉树 - 8、对称二叉树
递归法:
/**
* 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:
bool compare(TreeNode* left, TreeNode* right){
// 首先排除空节点的情况
if(left != NULL && right == NULL) return false;
else if(left == NULL && right != NULL) return false;
else if(left == NULL && right == NULL) return true;
else if(left->val != right->val) return false;
// 此时就是,左右节点都不为空且数值相等的情况
// 这个时候才做递归,做下一层的判断
bool outside = compare(left->left, right->right); // 左子树:左,右子树:右
bool inside = compare(left->right, right->left); // 左子树:右,右子树:左
bool isSame = outside && inside; // 左子树:中,右子树:中;逻辑判断
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return false;
return compare(root->left, root->right);
}
};
迭代法:用栈和队列都能做,代码是一样的
/**
* 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:
bool compare(TreeNode* left, TreeNode* right){
// 首先排除空节点的情况
if(left != NULL && right == NULL) return false;
else if(left == NULL && right != NULL) return false;
else if(left == NULL && right == NULL) return true;
else if(left->val != right->val) return false;
// 此时就是,左右节点都不为空且数值相等的情况
// 这个时候才做递归,做下一层的判断
bool outside = compare(left->left, right->right); // 左子树:左,右子树:右
bool inside = compare(left->right, right->left); // 左子树:右,右子树:左
bool isSame = outside && inside; // 左子树:中,右子树:中;逻辑判断
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return false;
return compare(root->left, root->right);
}
};
9、二叉树的最大深度
递归法:
后序
确定递归函数的参数和返回值:参数就是传入的根节点,返回值就是这棵树的高度,所以返回值是int型。
int getPath(treeNode* node);
确定递归出口:如果为空节点的话,就返回0,表示高度是0;
if(node == nullptr) return 0;
确定单层递归逻辑:先求它的左子树的深度,再求它的右子树的深度,然后取左右深度最大的数值,再+1(加1是因为算上当前中间节点)就是目前节点为根节点的数的深度。
int leftDepth = getPath(node->left);
int rightDepth = getPath(node->right);
int depth = 1 + max(leftDepth, rigthDepth);
return depth;
所以整体c++代码如下:
class Solution{
public:
int getPath(TreeNode* node){
if(node == nullptr) return 0;
int leftDepth = getPath(node->left); // 左
int rightDepth = getPath(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
}
int maxdepth(TreeNode* root){
return getPath(root);
}
};
代码精简之后:
class Solution{
public:
int maxdepth(TreeNode* root){
if(root == nullptr) return 0;
return 1 + max(getPath(node->left),getPath(node->right));
}
};
精简之后的代码根本看不出是哪种遍历方式,也看不出递归三部曲的步骤,所以如果对递归不是很熟练的话,尽量不要用这种装逼的代码!
前序(深度回溯)
本题当然也可以使用前序的方法来做,代码如下(充分表现出回溯的过程)
class Solution{
public:
int result = 0;
void getdepth(TreeNode* node, int depth){
result = result > depth ? result : depth; // 中
if(node->left == nullptr && node->right == nullptr) return;
if(node->left){ // 左
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯-1
}
if(node->right){ // 右
depth++; // 深度+1
getdepth(node->right, depth);
depth--; // 回溯-1
}
return;
}
int maxDepth(TreeNode* root){
if(root == nullptr) return result;
getdepth(root, 1);
return result;
}
};
以上是为了把细节体现出来,代码简化一下:
class Solution{
public:
int result = 0;
void getdepth(TreeNode* node, int depth){
result = result > depth ? result : depth; // 中
if(node->left == nullptr && node->right == nullptr) return;
if(node->left){ // 左
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯-1
}
if(node->right){ // 右
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯-1
}
return;
}
int maxDepth(TreeNode* root){
if(root == nullptr) return result;
getdepth(root, 1);
return result;
}
};
迭代法:
见 二叉树 - 5、二叉树的层序遍历 - 5.9、二叉树的最大深度
9.1、N 叉树的最大深度
递归法:
后序遍历
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
// 递归法:后序
class Solution {
public:
int maxDepth(Node* root) {
int depth = 0;
if(root == nullptr) return depth;
for(int i = 0; i < root->children.size(); i++){
if(root->children[i]){
depth = max(depth, maxDepth(root->children[i]));
}
}
return depth + 1;
}
};
前序(深度回溯)
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
// 递归法:前序(深度回溯)
class Solution {
public:
int result = 0;
void getPath(Node* node, int depth){
result = result > depth ? result : depth; // 中
if(node->children.size() == 0) return;
for(int i = 0; i < node->children.size(); i++){
if(node->children[i]){ // 从左到右
depth++; // 深度+1
getPath(node->children[i], depth);
depth--; // 回溯-1
}
}
return;
}
int maxDepth(Node* root) {
if(root == nullptr) return result;
getPath(root, 1);
return result;
}
};
迭代法
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
// 层序遍历法
class Solution {
public:
int maxDepth(Node* root) {
int depth = 0;
queue<Node*> que;
if(root == nullptr) return depth;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){ // 处理当前这一层的节点
Node* cur = que.front();
que.pop();
for(int j = 0; j < cur->children.size(); j++){
if(cur->children[j]){
que.push(cur->children[j]);
}
}
}
depth++;
}
return depth;
}
};
10、二叉树的最小深度
递归法:后序遍历
/**
* 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:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left = minDepth(root->left); // 左
int right = minDepth(root->right); // 右
// 中
// 当一个左子树为空,右子树不为空,这时左子树并不是最低点
if(root->left == nullptr && root->right != nullptr){
return 1 + right;
}
// 当一个左子树不为空,右子树为空,这时右子树并不是最低点
if(root->left != nullptr && root->right == nullptr){
return 1 + left;
}
return 1 + min(left, right);
}
};
迭代法
/**
* 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:
int minDepth(TreeNode* root) {
int minDepth = 0; // 记录二叉树的最小深度
queue<TreeNode*> que;
if(root == nullptr) return 0;
que.push(root);
minDepth++;
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size; i++){
TreeNode* cur = que.front();
que.pop();
if(!cur->left && !cur->right){
return minDepth;
}
else{
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
minDepth++;
}
return minDepth;
}
};
11、完全二叉树的节点个数
222. 完全二叉树的节点个数 - 力扣(LeetCode)
完全二叉树只有两种情况,
- 情况一:就是满二叉树
- 情况二:最后一层叶子节点没有满
对于情况一,可以直接用 2^树深度 - 1 来计算,注意,这里根节点的深度是1
对于情况二:分别递归其左孩子,右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况一来计算。
完全二叉树如图所示:
可以看出,如果一棵树不是满二叉树,就递归其左右孩子,知道遇到满二叉树为止,用公式计算这棵子树(满二叉树)的节点数量。
C++代码如下:
class Solution{
public:
int countNodes(TreeNode* root){
if(root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftHeight = 0, rightHeight = 0; // 这里初始化为0是有目的的,为了求下面指数方便
// 求左子树的深度
while(left){
left = left->left;
leftHeight++;
}
// 求右子树的深度
while(right){
right = right->right;
rightHeight++;
}
if(leftHeight == rightHeight){
return (2 << leftHeight) - 1; // 注意 (2 << 1) 相当于 2^2,所以leftHeight初始化为0
}
// 如果当前节点所在的二叉树不是满二叉树
return countNodes(root->left) + countNodes(root->right) + 1; // 1表示当前二叉树的根节点,需要加上
}
};
12、平衡二叉树
题外话
因为求深度可以从上到下去查,所以通常使用前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中)。所以在求二叉树的最大深度中,正确的逻辑应该是使用深度回溯的方法来解决。
本题思路
递归
此时大家应该明白了既然要求比较高度,必然是要前序遍历。
递归三部曲:
- 明确递归的参数和返回值
- 参数:当前传入节点
- 返回值:以当前传入节点为根节点的二叉树的高度。
那么如何标记左右子树的高度差大于1呢?
如果当前传入节点为根节点的二叉树已经不是二叉平衡树了,继续返回树的高度的话已经没有意义了。
所以如果已经不是二叉平衡树了,可以返回-1来标记已经不符合平衡树的规则了。
int getHeight(TreeNode* node);
- 明确终止条件
- 递归的过程依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树的高度为0
if(node == nullptr) return 0;
- 明确单层递归的逻辑
- 如何判断以当前传入节点的二叉树是否是平衡二叉树呢?当然是左右子树的高度差大于1 ```cpp int leftHeight = getHeight(node->left); // 左 if(leftHeight == -1) return -1; int rightHeight = getHeight(node->right); // 右 if(rightHeight == -1) return -1;
int result; if(abs(leftHeight - rightHeight) > 1){ // 中 result = -1; } else{ result = 1 + max(leftHeight, rightHeight); // 以当前节点为根节点的树的最大高度 } return result;
代码精简之后:
```cpp
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
此时递归的函数就已经写出来了,这个递归的函数传入节点指针,返回以该节点为根节点的二叉树的高度,如果不是二叉平衡树,则返回-1。
getHeight整体代码如下:
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;
}
int leftHeight = getHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if (rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
}
本题的整体递归代码如下:
class Solution{
public:
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了返回-1
int getHeight(TreeNode* node){
if(node == nullptr) return 0;
int leftHeight = getHeight(node->left);
if(leftHeight == -1) return -1;
int rightHeight = getHeight(node->right);
if(rightHeight == -1) return -1;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight,rightHeight);
}
bool isBalanced(TreeNode* node){
return getHeight(root) == -1 ? false : true;
}
};
迭代
在 104. 二叉树的最大深度 中,我们可以使用层序遍历来求深度,但是就是不能直接使用层序遍历来求高度,这就体现出求高度和求深度的不同。
本题的迭代方法可以先定义一个函数,专门用来求高度。
这个函数通过栈模拟的后序遍历找每一个节点的高度(其实就是通过传入节点为根节点的最大深度来求的高度)
代码如下:
// cur节点的最大深度,就是cur的高度
int getDepth(TreeNode* cur) {
stack<TreeNode*> st;
if (cur != NULL) st.push(cur);
int depth = 0; // 记录深度
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
if (node != NULL) {
st.pop();
st.push(node); // 中
st.push(NULL);
depth++;
if (node->right) st.push(node->right); // 右
if (node->left) st.push(node->left); // 左
} else {
st.pop();
node = st.top();
st.pop();
depth--;
}
result = result > depth ? result : depth;
}
return result;
}
然后再用栈来模拟前序遍历,遍历每一个节点的时候,再去判断左右孩子的高度是否符合,代码如下:
bool isBalanced(TreeNode* root){
stack<TreeNode*> st;
if(root == nullptr) return true;
st.push(root);
while(!st.empty()){
TreeNode* cur = st.top(); // 中
st.pop();
if(abs(getDepth(root->left) - getDepth(root->right)) > 1){
return false;
}
if(node->right) st.push(node->right); // 右
if(node->left) st.push(node->left); // 左
}
return true;
}
13、二叉树的所有路径
思路:
这道题要求从根节点到叶子节点的路径,所以需要前序遍历,这样才方便让父节点指向孩子节点,找到对应的路径。
在这道题目中第一次涉及到回溯,因为我们要把路径记录下来,需要回溯来回退一个路径后再进入另一个路劲。
前序遍历以及回溯的过程如下:
我们先使用递归的方式来做前序遍历。要知道递归和回溯本来就是一家的,本题也需要使用到回溯。
递归
- 递归函数的参数以及返回值
要传入根节点,记录每一条路径的path,和存放结果集的result,这里的递归不需要返回值,代码如下:
void traversal(TreeNode* cur, vector<int>& path, vector<string>& result)
- 确定递归的终止条件
本题的终止条件就是找到了叶子节点,即当cur不为空,且其左右孩子都为空的情况下,就算找到叶子节点
if(cur->left == nullptr && cur->right == nullptr){
终止处理逻辑;
}
为什么没有判断cur是否为空呢?因为下面的逻辑可以控制空节点不进入循环。
再来看一下终止处理的逻辑。
这里使用vector结构path来记录路径,所以要把vector结构的path转为string格式,再把这个string放入result里。
那么为什么使用了vector结构来记录路径呢?因为在下面处理单层递归逻辑的时候,要做回溯,使用vector方便来做回溯。
可能有的同学问了,我看有些人的代码也没有回溯啊。其实是有回溯的,只不过隐藏在函数调用时的参数赋值里了,下文我还会提到。
这里我们先使用vector结构的path容器来记录路径,那么终止处理逻辑如下:
if(cur->left == nullptr && cur->right == nullptr){ // 遇到叶子节点
string sPath;
for(int i = 0; i < path.size() - 1; i++){ // 将path里记录的路径转为string格式
sPath += std::to_string(path[i]);
sPath += "->";
}
sPath += std::to_string(path[path.size() - 1]); // 记录最后一个节点
result.push_back(sPath); // 收集一个路径
return;
}
- 确定单层递归逻辑
因为是前序遍历,需要先处理中间节点,中间节点就是我们要记录路径上的节点,先放进path中。
path.push_back(cur->val);
然后是递归和回溯的过程,上面说过没有判断cur是否为空,那么在这里递归的时候,如果为空就不进行下一层递归了。
所以递归前要加上判断语句,下面要递归的节点是否为空,如下
if (cur->left) {
traversal(cur->left, path, result);
}
if (cur->right) {
traversal(cur->right, path, result);
}
此时还没完,递归完,要做回溯啊,因为path 不能一直加入节点,它还要删节点,然后才能加入新的节点。
那么回溯要怎么回溯呢,一些同学会这么写,如下:
if (cur->left) {
traversal(cur->left, path, result);
}
if (cur->right) {
traversal(cur->right, path, result);
}
path.pop_back();
这个回溯就要很大的问题,我们知道,回溯和递归是一一对应的,有一个递归,就要有一个回溯,这么写的话相当于把递归和回溯拆开了, 一个在花括号里,一个在花括号外。
if (cur->left) {
traversal(cur->left, path, result);
path.pop_back(); // 回溯
}
if (cur->right) {
traversal(cur->right, path, result);
path.pop_back(); // 回溯
}
所以整体代码如下:
/**
* 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:
// 1.参数类型和返回值类型
// 2.递归出口
// 3.单层递归逻辑
void getPath(TreeNode* node, vector<int>& path, vector<string>& result){
path.push_back(node->val);
// 递归出口
if(node->left == nullptr && node->right == nullptr){
string sPath;
for(int i = 0; i < path.size() - 1; i++){
sPath = sPath + std::to_string(path[i]);
sPath = sPath + "->";
}
sPath = sPath + std::to_string(path[path.size() - 1]);
result.push_back(sPath);
return;
}
if(node->left){
getPath(node->left, path, result);
path.pop_back();
}
if(node->right){
getPath(node->right, path, result);
path.pop_back();
}
return;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> result;
getPath(root, path, result);
return result;
}
};
迭代法
/**
* 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<string> binaryTreePaths(TreeNode* root) {
stack<TreeNode*> treeSt; // 保存遍历树的结点
stack<string> pathSt; // 保存访问的路径
vector<string> result; // 保存最终正确路径的结果集
if(root == nullptr) return result;
treeSt.push(root);
pathSt.push(std::to_string(root->val));
while(!treeSt.empty()){
TreeNode* node = treeSt.top(); // 中
treeSt.pop();
string path = pathSt.top();
pathSt.pop();
if(node->left == nullptr && node->right == nullptr){
result.push_back(path);
}
if(node->right){ // 右
treeSt.push(node->right);
pathSt.push(path + "->" + std::to_string(node->right->val));
}
if(node->left){ // 左
treeSt.push(node->left);
pathSt.push(path + "->" + std::to_string(node->left->val));
}
}
return result;
}
};
14、二叉树周末总结
想偷懒,总结还是去看代码随想录吧:代码随想录 - 二叉树 - 14、二叉树周末总结