2021.01.08 重建二叉树

今日题目:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
image.png
限制:0 <= 节点个数 <= 5000

  • 思路:
    1. 法一:因为前序遍历序列的第一个元素就是树的根节点,然后在中序遍历序列中查找,返回查找到的数组下标,以此为分界线,将中序遍历序列划分为左右两个子数组,左数组为该根节点的左子树,右数组即为该根结点的右子树。再对左右两个子树进行同样的操作。本方法中传递递归调用的参数时(即子树的前序遍历序列和后序遍历序列,采用的是java中Arrays.copyOfRange(original, from, to) 方法,但是这个方法会新建一个子数组,大大增加空间复杂度,,而且每次在中序遍历序列中进行根节点索引的查找使得时间复杂度大大增加,可以再改进)。
    2. 法二(好了我又来评论区看大佬的代码了,叹为观止,每天都在被大佬震惊):前序遍历的首元素是树的根节点,然后在中序遍历序列找到根结点对应的下标,进而把中序遍历序列划分为左右两棵子树,即[ 左子树 | 根节点 | 右子树 ],然后根据中序遍历序列的划分结果确定左右子树的节点数量,进而对前序遍历序列进行划分,即[ 根节点 | 左子树 | 右子树 ]。而对于左右子树,仍可以用相同的方法继续进行划分,这是分治算法的体现。
    • 递推算法解析:
      • 递推参数:根节点在前序遍历序列中的数组下标 root,子树在中序遍历序列中的左边界 left,子树在中序遍历序列中的右边界 right。
      • 终止条件:left > right。表示已经越过叶子结点,此时返回null。
      • 递推工作:建立根节点,根结点值为preorder[root];划分左右子树为了提升效率,本文使用哈希表存储中序遍历的值与索引的映射,查找操作的时间复杂度为 O(1);构建左右子树,开始递归。
      • 返回值: 回溯返回 node,作为上一层递归中根节点的左 / 右子节点。 | | 根节点数组下标 | 中序遍历序列左边界 | 中序遍历序列右边界 | | —- | —- | —- | —- | | 左子树 | root+1 | left | index - 1 | | 右子树 | root + index - left + 1
        (根节点索引 + 左子树长度 + 1) | index + 1 | right |
  • 自己的菜鸡代码: ```java /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
    • TreeNode left;
    • TreeNode right;
    • TreeNode(int x) { val = x; }
    • } */ // 法一:太烂了,与法二形成鲜明对比 class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) {

      1. // 终究是要面对的,树的结构很多可用递归的方法解决
      2. if(preorder.length == 0)return null;
      3. TreeNode root = new TreeNode(preorder[0]);
      4. // 求出的index表示左子树的长度
      5. int index = findIndex(inorder,preorder[0]);
      6. // 存在左子树 copyOfRange,若是to的位置超过了数组的长度,则其余位置自动补0
      7. if(index != 0)
      8. root.left = buildTree(Arrays.copyOfRange(preorder, 1, index + 1), Arrays.copyOfRange(inorder, 0, index));
      9. // 存在右子树
      10. if(index != inorder.length-1)
      11. root.right = buildTree(Arrays.copyOfRange(preorder, index + 1, preorder.length), Arrays.copyOfRange(inorder,index+1, inorder.length));
      12. return root;

      }

      public int findIndex(int []nums, int x){

      1. for(int i = 0; i < nums.length; i++)
      2. if(nums[i] == x) return i;
      3. // 照理说不会出现这种情况,因为一个是前序遍历,一个是中序遍历
      4. return -1;

      } }

// 法二 class Solution { private int []preorder; private HashMap map = new HashMap<>(); public TreeNode buildTree(int[] preorder, int[] inorder) { this.preorder = preorder; for(int i = 0; i < inorder.length; i++){ map.put(inorder[i],i); } return build(0, 0, inorder.length - 1); }

  1. TreeNode build(int root, int left, int right){
  2. // root是在preorder中的数组下标值,left是树对应的中序遍历序列的最左下标值,right是树对应的中序遍历序列中的最右下标值
  3. if(left > right) return null;
  4. TreeNode ret = new TreeNode(preorder[root]);
  5. int index = map.get(preorder[root]);
  6. ret.left = build(root + 1 , left, index - 1);
  7. ret.right = build(root + index - left + 1, index + 1 , right);
  8. return ret;
  9. }

}

  1. - 运行结果:
  2. 法一(左):这个代码是真的烂,giao命。法二(右):太强了,真的太强了。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610097220814-071ecf1d-d6e4-49a5-9ce1-1521f463c911.png#align=left&display=inline&height=293&margin=%5Bobject%20Object%5D&name=image.png&originHeight=466&originWidth=636&size=28895&status=done&style=none&width=400)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610345452195-bc97bbb6-7a2d-4f33-8822-35ff6497b5e0.png#align=left&display=inline&height=293&margin=%5Bobject%20Object%5D&name=image.png&originHeight=455&originWidth=631&size=28782&status=done&style=none&width=406)
  3. <a name="pTAOT"></a>
  4. ### 2021.01.11 树的子结构(不简单)
  5. 今日题目:<br />输入两棵二叉树AB,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)<br />BA的子结构, A中有出现和B相同的结构和节点值。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610349179842-81e63663-1876-40f0-8ec4-ed0fc0a13260.png#align=left&display=inline&height=298&margin=%5Bobject%20Object%5D&name=image.png&originHeight=324&originWidth=456&size=10650&status=done&style=none&width=420)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610349209445-e7c9ca7d-be02-4cc5-a2eb-51ca9652e132.png#align=left&display=inline&height=247&margin=%5Bobject%20Object%5D&name=image.png&originHeight=250&originWidth=373&size=7789&status=done&style=none&width=368)<br />限制:0 <= 节点个数 <= 10000
  6. - 思路:dbq,这个算法是看了大佬的代码,自己也知道是用递归来做这个题,但是自己原来的想法是先在A中找到B所在的子树,然后再递归查看是否是A子树的子树。这题大佬的思路好难描述giao命,那俺就原样copy大佬的思想了(俺太菜了)。
  7. ===================================================================================
  8. - 解题思路:
  9. 若树 B 是树 A 的子结构,则子结构的根节点可能为树 A 的任意一个节点。因此,判断树 B 是否是树 A 的子结构,需完成以下两步工作:<br />先序遍历树 A 中的每个节点 n(对应函数 isSubStructure(A, B))<br />判断树 A n为根节点的子树 是否包含树 B 。(对应函数 recur(A, B))
  10. - recur(A, B) 函数:
  11. - 终止条件:
  12. - 当节点 B 为空:说明树 B 已匹配完成(越过叶子节点),因此返回 true
  13. - 当节点 A 为空:说明已经越过树 A 叶子节点,即匹配失败,返回 false
  14. - 当节点 A B 的值不同:说明匹配失败,返回 false
  15. - 返回值:
  16. - 判断 A B 的左子节点是否相等,即 recur(A.left, B.left)
  17. - 判断 A B 的右子节点是否相等,即 recur(A.right, B.right)
  18. - isSubStructure(A, B) 函数:
  19. - 特例处理: A 为空 B 为空 时,直接返回 false
  20. - 返回值: 若树 B 是树 A 的子结构,则必满足以下三种情况之一,因此用或 || 连接;
  21. - 节点 A 为根节点的子树 包含树 B ,对应 recur(A, B);
  22. - B A 左子树 的子结构,对应 isSubStructure(A.left, B);
  23. - B A 右子树 的子结构,对应 isSubStructure(A.right, B);
  24. 以上实质上是在对树 A 做先序遍历 <br />==================================================================================
  25. - 大佬的代码(不是我自己想的5555):
  26. ```java
  27. /**
  28. * Definition for a binary tree node.
  29. * public class TreeNode {
  30. * int val;
  31. * TreeNode left;
  32. * TreeNode right;
  33. * TreeNode(int x) { val = x; }
  34. * }
  35. */
  36. class Solution {
  37. public boolean isSubStructure(TreeNode A, TreeNode B) {
  38. // dbq 还是看了大佬的代码,大佬太强了55555555,这就是强者的世界吗
  39. // &&的后半部分实质上就是树的后根遍历
  40. return (A != null && B != null) && (recur(A,B) || isSubStructure(A.left,B) || isSubStructure(A.right,B));
  41. }
  42. boolean recur(TreeNode A, TreeNode B){
  43. // B已经遍历结束代表B是A的子结构
  44. if(B == null) return true;
  45. // A已经越过子结点或者A与B的结点值不一样,则返回false,
  46. if(A == null || A.val != B.val) return false;
  47. // 对A的左子树继续查看,对B的右子树继续查看
  48. return (recur(A.left, B.left) && recur(A.right, B.right));
  49. }
  50. }
  • 运行结果:

image.png

2021.01.11 二叉树的镜像(简单)

今日题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。(要改变结构)
image.png
限制:0 <= 节点个数 <= 1000

  • 思路:
    • 法一:利用递归,先对二叉树的左子树进行递归处理实现镜像,再对二叉树的右子树进行递归处理实现镜像,最后交换左右子树的位置,即完成整颗二叉树的镜像处理(啊哈哈哈自己写出来啦,没有看大佬的代码555555555555555)。这题的实质是树的后根遍历,先对树的子树进行处理,再对根进行处理。
      • mirrorTree(root)函数:
        • 递归结束的条件:结点为空
        • 返回值:已经进行镜像处理的树的根节点
        • 时间复杂度为O(n),空间复杂度为O(n)
    • 法二:利用队列,无需递归。实质上是树的层次遍历。
      • 算法流程:
        • 特例处理: 当 root 为空时,直接返回 null;
        • 初始化: 初始化队列并加入根节点 root 。
        • 循环交换: 当队列queue为空时跳出;
        • 出队: 记为 temp ;
        • 交换: 交换 temp 的左 / 右子节点。
        • 添加子节点: 将 temp 左和右子节点入队;
        • 返回值: 返回根节点 root。
        • 时间复杂度O(n),空间复杂度为O(n)
  • 自己的菜鸡代码: ```java /**
    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
    • TreeNode left;
    • TreeNode right;
    • TreeNode(int x) { val = x; }
    • } */ // 法一(递归) class Solution { public TreeNode mirrorTree(TreeNode root) {
      1. if(root == null) return null;
      2. root.left = mirrorTree(root.left);
      3. root.right = mirrorTree(root.right);
      4. TreeNode temp = root.left;
      5. root.left = root.right;
      6. root.right = temp;
      7. return root;
      } }

// 法二(队列) class Solution { public TreeNode mirrorTree(TreeNode root) { if(root == null) return null; LinkedList queue = new LinkedList<>(); queue.addLast(root); TreeNode temp, middle; while(!queue.isEmpty()){ temp = queue.poll(); if(temp == null || temp.left == null && temp.right == null) continue; middle = temp.left; temp.left = temp.right; temp.right = middle; queue.addLast(temp.left); queue.addLast(temp.right); } return root; } }

  1. - 运行结果:
  2. 法一(左)、法二(右)<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610357830287-5d936c53-3990-4453-a387-f3df74e0ca58.png#align=left&display=inline&height=272&margin=%5Bobject%20Object%5D&name=image.png&originHeight=448&originWidth=640&size=28573&status=done&style=none&width=389)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610416456290-387452f5-fdd1-4a44-9606-74cc30a9ad4b.png#align=left&display=inline&height=289&margin=%5Bobject%20Object%5D&name=image.png&originHeight=444&originWidth=629&size=28473&status=done&style=none&width=409)
  3. <a name="p56ld"></a>
  4. ### 2021.01.12 从上往下打印二叉树
  5. 今日题目:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610419179341-72208919-ce21-4c56-9f18-0b9170c9720e.png#align=left&display=inline&height=315&margin=%5Bobject%20Object%5D&name=image.png&originHeight=330&originWidth=325&size=7919&status=done&style=none&width=310)<br />提示:节点总数 <= 1000
  6. - 思路:暴力解决,本质上就是代码的层次遍历。层次遍历需要用到一个辅助队列,同时因为事先不知道树的结点数量,故用一个辅助的list类型来记录结点的值。
  7. - 算法流程:
  8. - 初始化: 初始化队列并加入根节点 root,初始化 list
  9. - 循环交换: 当队列 queue 为空时跳出;
  10. - 出队: 记为 temp
  11. - 添加子节点: temp 不为空,则将 temp 左和右子节点入队,同时用 list 记录 temp 的值;
  12. - 后续处理:初始化结果数组 result ,将 list 中的值逐个放到 result 中。
  13. - 返回值: 返回表示层序遍历结点值的数组 result
  14. - 时间复杂度O(n),空间复杂度为O(n)。
  15. - 自己的菜鸡代码:
  16. ```java
  17. /**
  18. * Definition for a binary tree node.
  19. * public class TreeNode {
  20. * int val;
  21. * TreeNode left;
  22. * TreeNode right;
  23. * TreeNode(int x) { val = x; }
  24. * }
  25. */
  26. class Solution {
  27. public int[] levelOrder(TreeNode root) {
  28. LinkedList<TreeNode> queue = new LinkedList<>();
  29. List<Integer> list = new ArrayList<>();
  30. queue.addLast(root);
  31. TreeNode temp;
  32. int count = 0;
  33. while(!queue.isEmpty()){
  34. temp = queue.poll();
  35. if(temp != null){
  36. list.add(temp.val);
  37. queue.addLast(temp.left);
  38. queue.addLast(temp.right);
  39. }
  40. }
  41. int[] result = new int[list.size()];
  42. for(int i = 0; i < list.size(); i++){
  43. result[i] = list.get(i);
  44. }
  45. return result;
  46. }
  47. }
  • 运行结果:

image.png

2021.01.12 从上到下打印二叉树II

今日题目:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
image.pngimage.png
提示:节点总数 <= 1000

  • 思路:
    • 法一:自己的思路。可以用两个队列来交替存放每一行的结点,从而实现同一层的节点按从左到右的顺序打印,每一层打印到一行的效果但是这样子时间复杂度好高🆘。照理来说时间复杂度为O(n),空间复杂度为O(n),运行结果应该还可以,没想到这么差。
    • 法二:本质上也是树的层次遍历。但是巧妙的利用队列的长度来区分不同层的结点。时间复杂度为O(n),空间复杂度也为O(n)。
  • 自己的菜鸡代码: ```java /**
    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
    • TreeNode left;
    • TreeNode right;
    • TreeNode(int x) { val = x; }
    • } */ // 法一(可以再改进 class Solution { public List> levelOrder(TreeNode root) {
      1. // 想到一种用空间换时间的方法,先试一下,这题比较烦的地方就是要把每层分隔开
      2. // 本来想用两个队列,交替进行
      3. List<List<Integer>> list = new ArrayList<>();
      4. LinkedList<TreeNode> queue1 = new LinkedList<>();
      5. LinkedList<TreeNode> queue2 = new LinkedList<>();
      6. queue1.addLast(root);
      7. TreeNode temp;
      8. List<Integer> data;
      9. while(!queue1.isEmpty() || !queue2.isEmpty()){
      10. data = new ArrayList<>();
      11. while(!queue1.isEmpty()){
      12. temp = queue1.poll();
      13. if(temp != null){
      14. data.add(temp.val);
      15. queue2.addLast(temp.left);
      16. queue2.addLast(temp.right);
      17. }
      18. }
      19. if(data.size() > 0) list.add(data);
      20. data = new ArrayList<>();
      21. while(!queue2.isEmpty()){
      22. temp = queue2.poll();
      23. if(temp != null){
      24. data.add(temp.val);
      25. queue1.addLast(temp.left);
      26. queue1.addLast(temp.right);
      27. }
      28. }
      29. if(data.size() > 0) list.add(data);
      30. }
      31. return list;
      } }

// 法二,大佬改进版本,只需用到一个栈即可。 class Solution { public List> levelOrder(TreeNode root) { List> list = new ArrayList<>(); LinkedList queue = new LinkedList<>(); List data; TreeNode temp; if(root != null) queue.addLast(root); while(!queue.isEmpty()){ data = new ArrayList<>(); for(int i = queue.size(); i > 0 ; —i){ temp = queue.poll(); data.add(temp.val); if(temp.left != null) queue.addLast(temp.left); if(temp.right != null) queue.addLast(temp.right); } list.add(data); } return list; } }

  1. - 运行结果:
  2. 法一:一个是在剑指中的运行结果,一个是在主站一道一样的题的运行结果,为什么差别会如此之大呢<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610422310813-83fc89be-db15-47ad-bfb2-b68a20531e7f.png#align=left&display=inline&height=281&margin=%5Bobject%20Object%5D&name=image.png&originHeight=459&originWidth=649&size=31140&status=done&style=none&width=397)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610437469826-7e02bca3-e4d3-49dc-a4e8-54d437859856.png#align=left&display=inline&height=285&margin=%5Bobject%20Object%5D&name=image.png&originHeight=472&originWidth=668&size=32209&status=done&style=none&width=403)<br />按照法二中的发现进行改动的结果,但是在主站中的运行结果如右图<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610438911804-09ab8967-ee95-4b7a-a6b6-3b403723e759.png#align=left&display=inline&height=293&margin=%5Bobject%20Object%5D&name=image.png&originHeight=461&originWidth=649&size=31648&status=done&style=none&width=412)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610438992447-804ef098-8b94-487f-b467-64770c68a09c.png#align=left&display=inline&height=296&margin=%5Bobject%20Object%5D&name=image.png&originHeight=535&originWidth=617&size=32033&status=done&style=none&width=341)<br />法二:为啥时间上都不太令人满意呢(我发现一点小小的问题)就是先声明再赋值与边声明边赋值的时间开销差别好大。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610439091806-0a11851b-b00f-4ca9-a998-b7cc7984e366.png#align=left&display=inline&height=330&margin=%5Bobject%20Object%5D&name=image.png&originHeight=572&originWidth=655&size=41227&status=done&style=none&width=378)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610439140586-6e0e1c32-8dde-4a69-9c1f-a2d7850b0361.png#align=left&display=inline&height=282&margin=%5Bobject%20Object%5D&name=image.png&originHeight=403&originWidth=552&size=32189&status=done&style=none&width=386)<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610438372031-58a054ca-4122-4747-9fc5-8964ab907d3c.png#align=left&display=inline&height=279&margin=%5Bobject%20Object%5D&name=image.png&originHeight=468&originWidth=652&size=31211&status=done&style=none&width=388)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610438599332-33983ac9-2cbe-4a7e-9375-8e7265a9b174.png#align=left&display=inline&height=269&margin=%5Bobject%20Object%5D&name=image.png&originHeight=412&originWidth=593&size=26464&status=done&style=none&width=387)
  3. <a name="S2G1D"></a>
  4. ### 2021.01.12 从上到下打印二叉树III
  5. 今日题目:请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610439319885-34610d0d-249f-46f8-ac68-6d44287205f0.png#align=left&display=inline&height=206&margin=%5Bobject%20Object%5D&name=image.png&originHeight=225&originWidth=302&size=5453&status=done&style=none&width=277)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610439332627-0f468fe1-0dd6-4206-9109-921232f53571.png#align=left&display=inline&height=185&margin=%5Bobject%20Object%5D&name=image.png&originHeight=201&originWidth=210&size=4050&status=done&style=none&width=193)<br />提示:节点总数 <= 1000
  6. - 思路:之字形从上到下打印二叉树实质上还是二叉树的层次遍历。这里利用的是双端队列、队列的长度、还有一个标记值来区分不同层的结点,从而实现最终结果。
  7. - 算法流程:
  8. - 初始化: 初始化队列并加入根节点 root,初始化 list
  9. - 循环交换: 当队列 queue 为空时跳出;
  10. - 区分从左到右还是从右到左:利用标记值的奇偶性,奇数则从左到右输出,偶数则从右到左输出。
  11. - 区分不同层的结点:用 i 记录记录队列的长度,即为某一层的节点数量。
  12. - 出队: 记为 temp ,并将temp的值存入data列表中;
  13. - 奇数层的处理:从队首出队,在孩子不为空的情况下在队尾存入左、右孩子(注意顺序)
  14. - 偶数层的处理:从队尾出队,在孩子不为空的情况下在队首存入右、左孩子(注意顺序)
  15. - 然后遍历完一层后将data存入list中。<br />
  16. - 返回值: 返回结果 list
  17. - 时间复杂度O(n),空间复杂度为O(n)。
  18. - 自己的菜鸡代码:
  19. ```java
  20. /**
  21. * Definition for a binary tree node.
  22. * public class TreeNode {
  23. * int val;
  24. * TreeNode left;
  25. * TreeNode right;
  26. * TreeNode(int x) { val = x; }
  27. * }
  28. */
  29. class Solution {
  30. public List<List<Integer>> levelOrder(TreeNode root) {
  31. // 本质上还是树的层次遍历
  32. // 可以利用双端队列
  33. List<List<Integer>> list = new ArrayList<>();
  34. LinkedList<TreeNode> queue = new LinkedList<>();
  35. if(root != null) queue.addLast(root);
  36. int flag = 1;
  37. while(!queue.isEmpty()){
  38. List<Integer> data = new ArrayList<>();
  39. if(flag % 2 == 1){
  40. for(int i = queue.size(); i > 0; --i){
  41. TreeNode temp = queue.poll();
  42. data.add(temp.val);
  43. if(temp.left != null) queue.addLast(temp.left);
  44. if(temp.right != null) queue.addLast(temp.right);
  45. }
  46. }else{
  47. for(int i = queue.size(); i > 0; --i){
  48. TreeNode temp = queue.removeLast();
  49. data.add(temp.val);
  50. if(temp.right != null) queue.addFirst(temp.right);
  51. if(temp.left != null) queue.addFirst(temp.left);
  52. }
  53. }
  54. ++flag;
  55. list.add(data);
  56. }
  57. return list;
  58. }
  59. }
  • 运行结果:

image.png

2021.01.12 二叉搜索树的后序遍历序列(这题有点难)

今日题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
image.pngimage.pngimage.png
提示:数组长度 <= 1000

  • 思路:后序遍历序列的结构为 左子树 | 右子树 | 根 ,所以可以利用递归的方式进行处理。❗这里是二叉搜索树❗,不是普通的二叉树。
  • 自己的菜鸡代码:
  • 运行结果

2021.01.18 二叉树的深度

今日题目(最近没学是我不对55):二叉树的深度

  • 思路:
    • 法一:利用递归解决(这题很简单)。若结点为空则返回0,若结点不为空则返回左子树高度和右子树之间高度较大的那个数+1的值。
    • 法二:非递归解决,采用队列进行层次遍历,设置一个计数器,每经过一层就进行+1
  • 自己的菜鸡代码: ```java /**
    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
    • TreeNode left;
    • TreeNode right;
    • TreeNode(int x) { val = x; }
    • } */ // 法一 class Solution { public int maxDepth(TreeNode root) {
      1. if(root == null) return 0;
      2. int left = maxDepth(root.left);
      3. int right = maxDepth(root.right);
      4. return 1 + (left > right? left : right);
      } }

// 法二 class Solution { public int maxDepth(TreeNode root) { // if(root == null) return 0; // int left = maxDepth(root.left); // int right = maxDepth(root.right); // return 1 + (left > right? left : right);

  1. // if(root == null) return 0;
  2. // return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
  3. if(root == null) return 0;
  4. LinkedList<TreeNode> queue = new LinkedList<>();
  5. queue.addLast(root);
  6. int count = 0;
  7. while(!queue.isEmpty()){
  8. for(int i = queue.size(); i > 0; --i){
  9. TreeNode temp = queue.poll();
  10. if(temp.left != null) queue.addLast(temp.left);
  11. if(temp.right != null) queue.addLast(temp.right);
  12. }
  13. ++count;
  14. }
  15. return count;
  16. }

}

  1. - 运行结果:
  2. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1610972223538-7edc4a2b-24ed-4590-9155-e77da48f942d.png#align=left&display=inline&height=326&margin=%5Bobject%20Object%5D&name=image.png&originHeight=457&originWidth=604&size=31166&status=done&style=none&width=431)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611020200897-d260dbc0-19c7-4680-a557-cccde39bd62b.png#align=left&display=inline&height=321&margin=%5Bobject%20Object%5D&name=image.png&originHeight=454&originWidth=650&size=32106&status=done&style=none&width=460)
  3. <a name="xGOOf"></a>
  4. ### 2021.01.20 对称的二叉树
  5. 今日题目:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611113077334-08b475ab-076a-4e4e-8366-9c8cc29f236d.png#align=left&display=inline&height=308&margin=%5Bobject%20Object%5D&name=image.png&originHeight=341&originWidth=406&size=10732&status=done&style=none&width=367)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611113099079-47f00add-8905-4794-83a6-37c0ad6ad8df.png#align=left&display=inline&height=252&margin=%5Bobject%20Object%5D&name=image.png&originHeight=252&originWidth=358&size=7907&status=done&style=none&width=358)<br />限制:0 <= 节点个数 <= 1000
  6. - 思路:
  7. - 法一:感觉本质上就是二叉树的层次遍历(写的贼烂)。使用两个双端队列,逐层比较。先是判断根节点是否为空,若不为空则在queue1的末端先后插入左孩子结点和右孩子结点。若queue1不为空或者queue2不为空,先处理queue1中的结点,同时从队首和队尾各poll一个结点,队首的记为left,队尾的记为right,若left == null right null,则继续循环,若是left != null right != nullleft.val == right.val则在queue2队首依次插入left的右孩子和左孩子,在队尾插入right的左孩子和右孩子。对queue2进行相同的处理,只是此时孩子结点是存入queue1中。
  8. - 法二:按照树的结构,肯定可以利用递归的方式来写,但是我不知道要怎么写救命。嘿嘿嘿,睡了一觉起来就知道怎么写了。先判断root是否为null,若是则直接返回true,若不是则继续。
  9. - 写了一个递归函数symmetry(TreeNode left, TreeNode right),left 表示对称部分的左边,right表示对称部分的右边。
  10. - 判断是否对称:
  11. 1. 传入的两个结点在都不为空的情况下,结点值若相等,则继续调用symmetry,返回left的左子树、right的右子树以及left的右子树、right的左子树对称性的相与结果。
  12. 1. 若两个结点都为空,则返回true
  13. 1. 其他情况返回false
  14. - 自己的菜鸡代码:
  15. ```java
  16. /**
  17. * Definition for a binary tree node.
  18. * public class TreeNode {
  19. * int val;
  20. * TreeNode left;
  21. * TreeNode right;
  22. * TreeNode(int x) { val = x; }
  23. * }
  24. */
  25. class Solution {
  26. public boolean isSymmetric(TreeNode root) {
  27. // 这种方法的时间复杂度和空间复杂度都好高,giao命
  28. // 本质上是层次遍历
  29. // 不对啊 为什么一直不行呢我就不明白了
  30. if(root == null) return true;
  31. LinkedList<TreeNode> queue1 = new LinkedList<>();
  32. LinkedList<TreeNode> queue2 = new LinkedList<>();
  33. queue1.addLast(root.left);
  34. queue1.addLast(root.right);
  35. while(!queue1.isEmpty() || !queue2.isEmpty()){
  36. for(int i = queue1.size(); i > 0; --i){
  37. TreeNode left = queue1.poll();
  38. TreeNode right = queue1.pollLast();
  39. if(left == null && right == null)continue;
  40. if(left != null && right != null && left.val == right.val){
  41. queue2.addFirst(left.right);
  42. queue2.addFirst(left.left);
  43. queue2.addLast(right.left);
  44. queue2.addLast(right.right);
  45. }
  46. else return false;
  47. }
  48. for(int i = queue2.size(); i > 0; --i){
  49. TreeNode left = queue2.poll();
  50. TreeNode right = queue2.pollLast();
  51. if(left == null && right == null)continue;
  52. if(left != null && right != null && left.val == right.val){
  53. queue1.addFirst(left.right);
  54. queue1.addFirst(left.left);
  55. queue1.addLast(right.left);
  56. queue1.addLast(right.right);
  57. }
  58. else return false;
  59. }
  60. }
  61. return true;
  62. }
  63. }
  64. // 法二 采用递归的方式
  65. class Solution {
  66. public boolean isSymmetric(TreeNode root) {
  67. if(root == null) return true;
  68. return symmetry(root.left, root.right);
  69. }
  70. boolean symmetry(TreeNode left, TreeNode right){
  71. if(left != null && right != null && left.val == right.val){
  72. return symmetry(left.left, right.right) && symmetry(left.right, right.left);
  73. }else if(left == null && right == null){
  74. return true;
  75. }else{
  76. return false;
  77. }
  78. }
  79. }
  • 运行结果:

法一(左)、法二(右)
image.pngimage.png

2021.01.21 平衡二叉树

今日题目:输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
image.pngimage.png
限制:1 <= 树的结点个数 <= 10000

  • 思路:
  1. 法一(本质上是先根遍历):是否可以利用递归呢。可以!!但是这个方法中时递归嵌套递归。isBalanced方法中需要调用height方法。本来想用HashMap来记录每个结点的高度值,但是看到评论区中有人说: java如果用hashmap来防止重复计算深度会慢很多…估计是因为例子都比较小 反而不停调用hashmap耗费了时间,故不采用。
    • isBalanced(TreeNode root):
      1. 若root == null,则返回true;
      2. 若左右子树的高度差大于1,返回false;
      3. 继续判断左右子树是否为平衡二叉树。
    • height(TreeNode root):
      1. 若root == null,则返回0;
      2. 否则将左右子树高度较大的值进行加一并返回。

大佬给了两种解决方法,法一的解决方法是其中一种,但是复杂度不知道要怎么分析,以下是大佬的分析:

复杂度分析: 时间复杂度 O(NlogN): 最差情况下(为“满二叉树”时),isBalanced(root) 遍历树所有节点,判断每个节点的深度 height(root) 需要遍历各子树的所有节点 。满二叉树高度的复杂度 O(logN) ,将满二叉树按层分为 log(N+1) 层; 空间复杂度 O(N): 最差情况下(树退化为链表时),系统递归需要使用 O(N)的栈空间。

  1. 法二(本质上是后序遍历):从底至顶返回子树深度,若判定某子树不是平衡,直接向上返回。
    • recur(root)函数:
      • 返回值:
      1. 当节点root左/右子树的深度差<= 1:则返回当前子树的深度,即节点root的左/右子树的深度最大值+1(max(left, right) + 1);
      2. 当节点root左/右子树的深度差>1:则返回-1,代表此子树不是平衡树,因此剪枝,直接返回-1;
    • isBalanced(root)函数:
      • 返回值:若recur(root) != -1,则说明此树平衡,返回true;否则返回false。
    • 复杂度
      • 时间复杂度:O(n),N为数的节点数;最差情况下,需要递归遍历树的所有节点。
      • 空间复杂度:O(n),最差情况下(树退化成链表),系统递归需调用O(n)的栈空间
  • 自己的菜鸡代码: ```java /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
    • TreeNode left;
    • TreeNode right;
    • TreeNode(int x) { val = x; }
    • } */ // 法一 class Solution { public boolean isBalanced(TreeNode root) {

      1. // 可以通过递归解决
      2. if(root == null) return true;
      3. if(Math.abs(height(root.left) - height(root.right)) > 1) return false;
      4. return isBalanced(root.left) && isBalanced(root.right);

      }

      int height(TreeNode root){

      1. if(root == null) return 0;
      2. return Math.max(height(root.left), height(root.right)) + 1;

      } }

// 法二 class Solution { public boolean isBalanced(TreeNode root) { return recur(root) != -1; }

  1. int recur(TreeNode root){
  2. if(root == null) return 0;
  3. int left = recur(root.left);
  4. if(left == -1) return -1;
  5. int right = recur(root.right);
  6. if(right == -1) return -1;
  7. return Math.abs(left - right) < 2? Math.max(left,right) + 1 : -1;
  8. }

}

  1. - 运行结果:
  2. 法一(左)、法二(右):<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611218435197-714c26d3-ab0e-402f-921c-3cb56d003469.png#align=left&display=inline&height=296&margin=%5Bobject%20Object%5D&name=image.png&originHeight=452&originWidth=627&size=28389&status=done&style=none&width=411)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611222678641-2b90875c-96f0-441a-8e20-93904b82c9ce.png#align=left&display=inline&height=304&margin=%5Bobject%20Object%5D&name=image.png&originHeight=461&originWidth=589&size=29329&status=done&style=none&width=388)
  3. <a name="1TBhZ"></a>
  4. ### 2021.01.22 二叉树的最近公共祖先
  5. 今日题目:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。(5555好难的样子救命)<br />百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 pq,最近公共祖先表示为一个结点 x,满足 x pq 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611280342462-0fe4415f-39ff-4d7d-913f-d143342c03b7.png#align=left&display=inline&height=284&margin=%5Bobject%20Object%5D&name=image.png&originHeight=285&originWidth=443&size=23097&status=done&style=none&width=442)![image.png](https://cdn.nlark.com/yuque/0/2021/png/1584832/1611280362177-08bcda4b-2bed-4867-8653-200fdec9f2b6.png#align=left&display=inline&height=304&margin=%5Bobject%20Object%5D&name=image.png&originHeight=323&originWidth=553&size=18259&status=done&style=none&width=521)<br />说明:
  6. - 所有节点的值都是唯一的。
  7. - pq 为不同节点且均存在于给定的二叉树中。
  8. - 思路:
  9. - 法一(本质上是先序遍历):救命救命时间复杂度和空间复杂度怎么这么高。递归中嵌套递归sos。先判断根节点是否是pq中的一个,若是,则直接返回pq;否则判断pq是否都在root 的左子树中,若都在则在左子树中继续寻找,若pq都在root的右子树中,则继续在右子树中寻找,若在不同子树中则返回root(最近公共祖先)。
  10. - lowestCommonAncestorrootpq):
  11. 返回值:<br />若 p == root,返回p;若q ==root,返回q;<br />若p q 同在左子树中,则继续返回lowestCommonAncestor(root.left, p, q);<br />若p q 同在右子树中,则继续返回lowestCommonAncestor(root.right, p, q);<br />若p q 在不同子树中,则返回root
  12. - contain(root, target):在以root为根的树中查找目标值target
  13. 返回值:<br />若root == null,返回false;<br />若root == target,返回true;<br />其他情况返回contain(root.left, target) || contain(root.right, target);
  14. - 法二:应该跟上一题一样,本质是后序遍历,可以采用从底向上的方式,但是我不会啊giao
  15. 通过这一题跟上一题,有的情况下可以采用先序遍历和后序遍历,但是先序遍历中总是存在递归的嵌套,时间复杂度和空间复杂度很高且不好分析,效率很差;关键是要会用后序遍历,这个很不好理解。
  16. - rootroot p, q 最近公共祖先 ,则只可能为以下情况之一:
  17. pqroot的两个子树中,且分列root的异侧。<br />p ==rootqroot的左右子树中。<br />q == rootproot的左右子树中。
  18. - 递归解析:
  19. - 终止条件:当越过叶节点时,直接返回null,当root等于pq时,直接返回root
  20. - 递推工作:
  21. 1. 开启递归左子节点,返回值记为left
  22. 1. 开启递归右子节点,返回值记位right
  23. - 返回值:根据leftright的值,可以分为四种情况:
  24. 3. leftright同时为空,说明root的左右子树中都不含pq,返回null
  25. 3. leftright同时不为空,说明pqroot的异侧,返回root
  26. 3. left为空、right不为空时,说明pq都不在root的左子树中,直接返回right。具体可以分为两种情况:pq其中一个为最近公共祖先,另一个在子树中;pq在不同的子树中,right指向最近公共祖先。
  27. - 自己的菜鸡代码:
  28. ```java
  29. /**
  30. * Definition for a binary tree node.
  31. * public class TreeNode {
  32. * int val;
  33. * TreeNode left;
  34. * TreeNode right;
  35. * TreeNode(int x) { val = x; }
  36. * }
  37. */
  38. // 法一
  39. class Solution {
  40. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  41. // 本质上是先根遍历。最近公共祖先无论如何都是存在的
  42. if(p == root) return p;
  43. if(q == root) return q;
  44. boolean leftContainP = contain(root.left, p);
  45. boolean leftContainQ = contain(root.left, q);
  46. if(leftContainP && leftContainQ){
  47. // 同在左子树中
  48. return lowestCommonAncestor(root.left, p, q);
  49. }
  50. if(leftContainP || leftContainQ){
  51. // 在不同子树中
  52. return root;
  53. }else{
  54. // 同在右子树中
  55. return lowestCommonAncestor(root.right, p, q);
  56. }
  57. }
  58. boolean contain(TreeNode root, TreeNode target){
  59. if(root == null) return false;
  60. if(root == target) return true;
  61. return contain(root.left, target) || contain(root.right, target);
  62. }
  63. }
  64. // 法二
  65. class Solution {
  66. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  67. if(root == null || root == p || root == q) return root;
  68. TreeNode left = lowestCommonAncestor(root.left, p, q);
  69. TreeNode right = lowestCommonAncestor(root.right, p, q);
  70. if(left == null && right == null) return null;
  71. if(left == null) return right;
  72. if(right == null) return left;
  73. return root;
  74. }
  75. }
  • 运行结果:

法一(左)、法二(右)
image.pngimage.png

2021.01.22 二叉搜索树的第k大结点

今日题目:给定一棵二叉搜索树,请找出其中第k大的节点。
image.pngimage.png
限制:1 ≤ k ≤ 二叉搜索树元素个数

  • 思路:(这题本质上就是树的中序遍历)关键是要一边遍历,一边计数,然后还要返回值,当找到第k大结点时就要提前结束递归。

    • 递归解析:
      • 终止条件:当root结点为空,结束递归。
      • 递归右子树;
      • 进行三步处理:先判断是否已经找到第k大的值,若是,则提前结束递归;若未找到,则进行 —k的操作,若此时k == 0,则用res记录root的值(表示当前结点为第k大的数)。
      • 递归左子树。
  • 自己的菜鸡代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. private int res;
    12. private int k;
    13. public int kthLargest(TreeNode root, int k) {
    14. // 中序遍历序列逆序
    15. this.k = k;
    16. inorder(root);
    17. return res;
    18. }
    19. void inorder(TreeNode root){
    20. if(root == null) return;
    21. inorder(root.right);
    22. if(k == 0) return;
    23. if(--k == 0) res = root.val;
    24. inorder(root.left);
    25. }
    26. }
  • 运行结果:

image.png

2021.02.17 二叉搜索树的后序遍历序列

今日题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
image.pngimage.pngimage.png
提示:数组长度 <= 1000

  • 思路:后序遍历序列的最后一个是根节点,而本棵树是二叉搜索树,这意味着左子树中的所有值都小于根节点的值,右子树中的所有值都大于根节点的值,从第一个元开始遍历,直至找到第一个大于根节点的值,以此为分界线将后序遍历序列划分为 左子树 | 右子树 | 根 ,继续往后遍历,若是在右子树中找到小于根节点的值,则返回false。否则继续对左子树(判断是否存在)与右子树(判断是否存在)进行递归操作。
  • 自己的菜鸡代码:

    1. class Solution {
    2. private int[] postorder;
    3. public boolean verifyPostorder(int[] postorder) {
    4. // 这题是用递归吗,我好困giao命 二叉搜索树的中序遍历序列是有序的
    5. // 关键就是如何分出左右子树
    6. if(postorder.length == 0)return true;
    7. this.postorder = postorder;
    8. return recur(0, postorder.length - 1);
    9. }
    10. boolean recur(int begin, int end){
    11. if(end - begin + 1 <= 0) return true;
    12. int root = postorder[end];
    13. int i = begin;
    14. for(; i < end; i++){
    15. if(postorder[i] > root) break;
    16. }
    17. int j = i;
    18. for(; j < end; j++){
    19. if(postorder[j] < root) return false;
    20. }
    21. //[4, 8, 6, 12, 16, 14, 10]
    22. boolean left = true;
    23. // 为什么要判断啊
    24. if(i > 0){
    25. left = recur(begin, i-1);
    26. }
    27. boolean right = true;
    28. if(i < end - 1){
    29. right = recur(i, j - 1);
    30. }
    31. return left && right;
    32. }
    33. }
  • 运行结果:

image.png