您的位置:首页 > 科技 > 能源 > Day23:Leetcode:530.二叉搜索树的最小绝对差 + 501.二叉搜索树中的众数 + 236. 二叉树的最近公共祖先

Day23:Leetcode:530.二叉搜索树的最小绝对差 + 501.二叉搜索树中的众数 + 236. 二叉树的最近公共祖先

2024/9/24 5:33:22 来源:https://blog.csdn.net/qq_43506087/article/details/138918402  浏览:    关键词:Day23:Leetcode:530.二叉搜索树的最小绝对差 + 501.二叉搜索树中的众数 + 236. 二叉树的最近公共祖先

LeetCode:530.二叉搜索树的最小绝对差

问题描述

解决方案:

1.思路

  • 中序遍历

2.代码实现

class Solution {int pre;int ans;public int getMinimumDifference(TreeNode root) {ans = Integer.MAX_VALUE;pre = -1;dfs(root);return ans;}public void dfs(TreeNode root) {if (root == null) {return;}dfs(root.left);if (pre == -1) {pre = root.val;} else {ans = Math.min(ans, root.val - pre);pre = root.val;}dfs(root.right);}
}

3.复杂度分析

在这里插入图片描述

5.疑问

  • 递归树不太会画,课后请教通哥

LeetCode:501.二叉搜索树中的众数

解决方案:

1.思路:

  • 中序遍历+hashMap,考虑优化使用hashMap的时间复杂度;
  • 考虑到二叉搜索树中序遍历的有序性,实现一个update函数,根据记录频率实现众数的记录与更新
首先更新base和base出现的次数count
  • 如果所遍历节点值x=base,那么count+1;
  • 如果不等于base,那么把base加入answer数组,然后令base=x,count=1;
然后更新maxcount
  • 如果count=maxcount,那么说明该该数字出现的次数和已经出现的众数出现的次数一样,就把该数base存入数组answer中;
  • 如果count>maxcount,那么需要将max更新为maxcount。
  • 并情况answer数组,将base加入数组中;

2.代码实现

class Solution {List<Integer> answer = new ArrayList<Integer>();int base, count, maxCount;public int[] findMode(TreeNode root) {dfs(root);int[] mode = new int[answer.size()];for (int i = 0; i < answer.size(); ++i) {mode[i] = answer.get(i);}return mode;}//中序遍历的逻辑public void dfs(TreeNode T) {if (T == null) {return;}dfs(T.left);update(T.val);dfs(T.right);}public void update(int x) {if (x == base) {++count;} else {count = 1;base = x;}if (count == maxCount) {answer.add(base);}if (count > maxCount) {maxCount = count;answer.clear();answer.add(base);}}
}

3.复杂度分析

在这里插入图片描述

3.复杂度分析

  • 一定要动手画递归树;

LeetCode: 236. 二叉树的最近公共祖先

问题描述

解决方案:

1.思路:

  • 后序遍历可以最后处理根节点,相当于记录根节点;
  • 递归终止逻辑是:根节点为空,那么说明不存在p和q;或者p和q其中一个和根节点一致,那么直接返回该根节点即可;
  • 然后进行递归遍历,去获得
  • 如果

2.代码实现

public class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if (root == null || root == p || root == q) {return root;}
//接住上一层传递回来的节点,要么是根据两个if语句返回的是root,要么是根据最后一句return,返回的是nullTreeNode left = lowestCommonAncestor(root.left, p, q);TreeNode right = lowestCommonAncestor(root.right, p, q);if (left != null && right != null) {return root;}return left != null ? left : right;}
}

3.复杂度分析

在这里插入图片描述

4.疑惑思考

  • 递归出口是null很重要;
  • 当前节点的左右节点接住了上一层入栈函数的返回函数,返回的是null;

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com