文章目录
【LeetCode热题100】打卡第30天:从前序遍历与中序遍历序列构造二叉树&二叉树展开为链表
⛅前言
大家好,我是知识汲取者,欢迎来到我的LeetCode热题100刷题专栏!
精选 100 道力扣(LeetCode)上最热门的题目,适合初识算法与数据结构的新手和想要在短时间内高效提升的人,熟练掌握这 100 道题,你就已经具备了在代码世界通行的基本能力。在此专栏中,我们将会涵盖各种类型的算法题目,包括但不限于数组、链表、树、字典树、图、排序、搜索、动态规划等等,并会提供详细的解题思路以及Java代码实现。如果你也想刷题,不断提升自己,就请加入我们吧!QQ群号:827302436。我们共同监督打卡,一起学习,一起进步。
博客主页💖:知识汲取者的博客
LeetCode热题100专栏🚀:LeetCode热题100
Gitee地址📁:知识汲取者 (aghp) - Gitee.com
Github地址📁:Chinafrfq · GitHub
题目来源📢:LeetCode 热题 100 - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台
PS:作者水平有限,如有错误或描述不当的地方,恳请及时告诉作者,作者将不胜感激
从前序与中序遍历构造二叉树
🔒题目
原题链接:105.从前序与中序遍历构造二叉树
🔑题解
-
解法一:递归
解题大致思路:首先我们需要明确,前序遍历的顺序都是 $ 根节点→左节点→右节点$,中序遍历的顺序都是 $ 左节点→根节点→右节点$,这个特性是实现递归的关键,我们可以利用这个特性,①先通过前序序列得到当前层的根节点,②然后通过中序序列根据这个根节点,划分出左右子树,递归地进行①和②两步,最终就可以构造出一颗完整的二叉树
示意图:
具体过程分析如下所示:
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] 首先根据 preorder 找到根节点是 3 然后根据根节点将 inorder 分成左子树和右子树 左子树 inorder [9] 右子树 inorder [15,20,7] 把相应的前序遍历的数组也加进来 左子树 preorder[9] inorder [9] 右子树 preorder[20 15 7] inorder [15,20,7] 现在我们只需要构造左子树和右子树即可,成功把大问题化成了小问题 然后重复上边的步骤继续划分,直到 preorder 和 inorder 都为空,返回 null 即可
这里有必要详细讲解一下左右区间划分的推导:
- 左子树区间范围的推导:
preorder[1,index+1)
:确定左侧边界(左侧的1怎么来的),前序遍历,preorder[0]必定是根节点,所以左子树的节点必定是从1开始的;确定右侧边界(右侧的 index+1怎么来的),右侧边界需要依据左子树节点的数量计算得到,而中序遍历正好划分了左右子树,所以左子树的数量就是 index ,由于 我们是从1开始计算的,所以 index 要 +1inorder[0,index)
:确定左侧边界(左侧的0怎么来的),中序遍历,index左侧全是左子树,所以从0开始;确定右侧边界(右侧的 index怎么来的),中序遍历 index 指向根节点,不能取,所以左侧是 index
- 右子树区间范围的推导:
preorder[index+1,preorder.length)
:正好是上面区间的补集inorder[index+1,inorder.length)
:同理,也是上面区间的补集,但是左边闭区间不能取 index,index是根节点
class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length == 0 || inorder.length == 0) { return null; } // 获取当前的根节点 TreeNode root = new TreeNode(preorder[0]); // 遍历前序序列,找出在根节点在中序序列中的位置 int index = 0; for (int i = 0; i < preorder.length; i++) { if (preorder[0] == inorder[i]) { index = i; break; } } // 构建左子树 root.left = buildTree(Arrays.copyOfRange(preorder, 1, index + 1), Arrays.copyOfRange(inorder, 0, index)); // 构建右子树 root.right = buildTree(Arrays.copyOfRange(preorder, index + 1, preorder.length), Arrays.copyOfRange(inorder, index + 1, inorder.length)); return root; } }
复杂度分析:
- 时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn),需要递归 l o g n logn logn次,每次都需要走一遍循环,循环最坏情况为 n n n,最好情况为1
- 空间复杂度: O ( l o g n ) O(logn) O(logn),递归 l o g n logn logn次,所需栈空间为 l o g n logn logn
其中 n n n 为数组中元素的个数
代码优化:
- 数据结构上的优化:上面的代码,我们每次递归都需要执行一次for循环去中序数组中定位根节点的位置,这个操作执行一遍还好,但是递归执行就十分费时间,这里直接使用一个HashMap进行映射,从而减少时间消耗
- 划分方式上的优化:上面代码,是直接调用
Arrays.copyOfRange
方法进行左右子树的划分,每次都需要遍历一遍原数组,耗费性能较低,并且每次调用都会重新创建一个数组对象,耗费内存,我们使用指针的方式来划分左右子树,在原数组的基础上实现左右数组的划分,既不用遍历数组又不要新建对象,从而减少时间和内存消耗
具体实现思路和上面是类似的,就是将上面比较直白的区间划分,改用指针来划分
import java.util.HashMap; import java.util.Map; /** * @author ghp * @title */ class Solution { private Map<Integer, Integer> map = new HashMap<>(16); public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length == 0 || inorder.length == 0) { return null; } // map用于映射节点的值与索引,方便快速定位 for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return buildTree(preorder, 0, preorder.length, inorder, 0, inorder.length); } /** * 构建二叉树 * * @param preorder 当前根节点的前序遍历 * @param preLeft 当前根节点前序遍历的左边界 * @param preRight 当前根节点前序遍历的右边界 * @param inorder 当前根节点的中序遍历 * @param inoLeft 当前根节点中序遍历的左边界 * @param inoRight 当前根节点中序遍历的右边界 * @return */ private TreeNode buildTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inoLeft, int inoRight) { if (preLeft == preRight) { return null; } TreeNode root = new TreeNode(preorder[preLeft]); // 定位当前根节点在中序遍历数组的具体位置 int index = map.get(root.val); // 计算左子树节点的数量 int leftNum = index - inoLeft; // 构建左子树 root.left = buildTree(preorder, preLeft + 1, preLeft + leftNum + 1, inorder, inoLeft, index); // 构建右子树 root.right = buildTree(preorder, preLeft + leftNum + 1, preRight, inorder, index + 1, inoRight); return root; } }
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n),遍历一遍数组,时间复杂度是 n n n,递归划分二叉树,时间复杂度是 l o g n logn logn,所以时间复杂度是 n + l o g n n+logn n+logn
- 空间复杂度: O ( n ) O(n) O(n),需要开闭一个Map集合空间复杂度是 n n n,递归空复杂度是 l o g n , 也就是树的高度 logn,也就是树的高度 logn,也就是树的高度,所以空间复杂度是 n + l o g n n+logn n+logn
其中 n n n 为数组中元素的个数
代码优化:和上一题类似
- 左子树区间范围的推导:
从中序与后序遍历构造二叉树
🔒题目
原题链接:106.从前序与中序遍历构造二叉树
🔑题解
-
解法一:递归
思路和上一题很类似,就是区间的划分有点不一样罢了
- 左子树区间范围的推导:
inorder[0,index)
:中序遍历,index正好是根节点索引,index左侧是左子树,index右侧是右子树postorder[0,index)
:确定左侧边界(左侧的1怎么来的),后序遍历,先左后右最后才是中间节点,所以左子树节点必定从 0 开始,边界就是 左子树的长度,也就是 index ,
- 右子树区间范围的推导:
inorder[index+1,n)
:中序遍历,index正好是根节点索引,index左侧是左子树,index右侧是右子树postorder[index,n-1)
:正好是上面区间的补集,但是需要排除最后一个节点,因为后序遍历最后一个节点是根节点
class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { // 递归终止条件 if (inorder.length == 0 || postorder.length == 0) { return null; } int n = postorder.length; // 后序遍历最后一个节点一定是根节点 TreeNode root = new TreeNode(postorder[n - 1]); // 定位中序数组中的根节点 int index = 0; for (int i = 0; i < inorder.length; i++) { if (inorder[i] == root.val){ index = i; break; } } // 构建左子树 root.left = buildTree(Arrays.copyOfRange(inorder, 0, index), Arrays.copyOfRange(postorder, 0, index)); // 构建左子树 root.right = buildTree(Arrays.copyOfRange(inorder, index+1, n), Arrays.copyOfRange(postorder, index, n-1)); return root; } }
复杂度分析:
- 时间复杂度: O ( n 2 ) O(n^2) O(n2)
- 空间复杂度: O ( 1 ) O(1) O(1)
其中 n n n 为数组中元素的个数
代码优化:和上一题的优化是一摸一样的,这里就不作过多讲解了,不懂的可以回看上一题
class Solution { private Map<Integer, Integer> map = new HashMap<>(16); public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder.length == 0 || postorder.length == 0) { return null; } // map用于节点的值与索引,方便快速定位 for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length); } private TreeNode buildTree(int[] inorder, int inoLeft, int inoRight, int[] postorder, int posLeft, int posRight) { if (posLeft == posRight) { return null; } // 后序遍历最后一个节点一定是根节点 TreeNode root = new TreeNode(postorder[posRight - 1]); // 定位中序数组中的根节点 int index = map.get(root.val); // 计算左子树的长度 int leftLen = index - inoLeft; // 构建左子树 root.left = buildTree(inorder, inoLeft, index, postorder, posLeft, posLeft + leftLen); // 构建右子树 root.right = buildTree(inorder, index + 1, inoRight, postorder, posLeft + leftLen, posRight - 1); return root; } }
- 左子树区间范围的推导:
二叉树展开为链表
🔒题目
原题链接:114.二叉树展开为链表
🔑题解
-
解法一:前序遍历
-
递归实现:
这个思路比较简单,算法详情请参考【LeetCode热题100】打卡第27天:二叉树的前序、中序、后序遍历
但是这个算法没有并不是原地修改二叉树,需要依赖额外的空间
class Solution { private List<Integer> list = new ArrayList<>(); public void flatten(TreeNode root) { if (root == null){ return; } // 前序遍历 preorderTraversal(root); TreeNode node = root; // 这里需要排除根节点,防止重复 list.remove(0); for (Integer value : list) { node.left = null; node.right = new TreeNode(value); node = node.right; } } private void preorderTraversal(TreeNode root) { if (root==null){ return; } list.add(root.val); preorderTraversal(root.left); preorderTraversal(root.right); } }
-
迭代实现:
class Solution { public void flatten(TreeNode root) { if (root == null) { // 防止后面出现NPE return; } // 迭代实现前序遍历 List<Integer> list = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; while (!stack.isEmpty() || cur != null) { while (cur != null) { list.add(cur.val); stack.push(cur); cur = cur.left; } TreeNode node = stack.pop(); cur = node.right; } cur = root; // 这里需要排除根节点,防止重复 list.remove(0); for (Integer value : list) { cur.left = null; cur.right = new TreeNode(value); cur = cur.right; } } }
两种实现方式的复杂度是一致的
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n),for循环遍历二叉树的所有节点,时间复杂度是 n n n,前序遍历遍历最好的情况(树是一颗完全平衡二叉树)时间复杂度是 l o g n logn logn最坏的情况(树是一个单链表)时间复杂度是 n n n,
- 空间复杂度: O ( n ) O(n) O(n),一个List集合存储所有节点,所需空间是 n n n
其中 n n n 为二叉树节点的数量
-
-
解法三:原地修改
-
递归实现
这里我就不画示意图了,详情可以在脑子里想象一下,代码注释也比较详细,可以一遍看代码,一边想象
class Solution { public void flatten(TreeNode root) { if (root == null) { return; } // 递归到左子树最底端 flatten(root.left); // 临时存储右子树,用于后面的递归 TreeNode right = root.right; // 将左子树移到右侧,左子树置空 root.right = root.left; root.left = null; // 右子树同样执行上面的操作,构造成只有右节点的树 flatten(right); // 将构造好的右子树 连接到 构造好的左子树的后面 while (root.right != null) { root = root.right; } root.right = right; } }
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n),最坏情况(树是单链表)时间复杂度 n n n,最好情况(树是完全平衡二叉树)时间复杂度 l o g n logn logn
- 空间复杂度: O ( n ) O(n) O(n),需要递归n次,栈空间需要n
其中 n n n 为二叉树节点的数量
-
指针实现
相较于递归实现,空间复杂度有所降低
备注:图片来源LeetCode官网,我自己稍作修改
class Solution { public void flatten(TreeNode root) { TreeNode cur = root; while (cur != null) { if (cur.left != null) { // 临时存储左子树,用于后面将左子树移动到右侧 TreeNode left = cur.left; // 将right指针指向左节点 右子树的最底端 TreeNode right = cur.left; while (right.right != null){ right = right.right; } // 将右子树连接到左节点右子树的后面 right.right = cur.right; // 左子树置空,将右子树移动到左侧 cur.left = null; cur.right = left; } cur = cur.right; } } }
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n),其中是二叉树的节点数。展开为单链表的过程中,需要对每个节点访问一次,在寻找前驱节点的过程中,每个节点最多被额外访问一次。
- 空间复杂度: 0 ( 1 ) 0(1) 0(1)
-
拓展
最开始我们从
前序 + 中序 ===> 二叉树
,后面我们又从中序 + 后序 ===> 二叉树
,而现在我们学会将二叉树重新构造成只有右节点的树
,那么我们能不能实现将二叉树重新构造成只有左节点的树
呢?快来动手实现一下吧(●ˇ∀ˇ●),很多时候好学会举一反三,很多东西都是相通的,不能一味的只刷题把思维给固化了,我们要学会举一反三,这样刷一题胜过刷百题