Day16
二叉树part06
LeetCode 530.二叉搜索树的最小绝对差
题目描述
给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例

输入:root = [4,2,6,1,3]
输出:1
题目链接
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
思路
给的是二叉搜索树, 因此采用中序遍历, 这样的得到的结果顺序是升序的。
因此, 求最小差值一定是相邻的两个节点的值。先初始化一个最大值Integer.MAX_VALUE
, 使用pre
记录上一个节点, 每次用root.val - pre.val
比较和已经记录的result
进行比较, 存入小的数。即可求解
解决代码
class Solution {int result = Integer.MAX_VALUE;TreeNode pre = null;public int getMinimumDifference(TreeNode root) {if(root == null){return 0;}traveral(root);return result;}public void traveral(TreeNode root){if(root == null){return;}traveral(root.left);if(pre != null){result = Math.min(result, root.val - pre.val);}pre = root;traveral(root.right);}
}
LeetCode 501.二叉搜索树中的众数
题目描述
给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
示例

输入:root = [1,null,2,2]
输出:[2]
题目链接
https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
思路
给的是一个含重复值的二叉搜索树,依旧采用中序遍历,这样遍历得到的结果,是有序的。
初始化一个链表,用于存储众数值,再使用count
记录每次出现的次数, MAXCount
记录众数值。前驱节点和当前节点相同,count
自增, 否则置为一。比较当前记录的次数是否大于MAXCount
是则替换
解决代码
class Solution {TreeNode pre = null;ArrayList<Integer> reslist = new ArrayList<>();//存储结果,题目明确,可能不止一个众数int count = 0;//记录出现次数int MAXCount = 0;//记录最多出现的次数public int[] findMode(TreeNode root) {travesal(root);int[] res = new int[reslist.size()];//链表转换为数组输出for(int i = 0; i < reslist.size(); i++){res[i] = reslist.get(i);}return res;}public void travesal(TreeNode root){if(root == null){return;}travesal(root.left);if(pre == null || pre.val != root.val){count = 1;}else{count++;}//更新结果if(count > MAXCount){reslist.clear();reslist.add(root.val);MAXCount = count;}else if(count == MAXCount){reslist.add(root.val);}pre = root;travesal(root.right);}
}
LeetCode 236. 二叉树的最近公共祖先
题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
示例

输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
题目链接
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
思路
- 递归终止条件:当前节点为空或等于p/q时返回。
- 递归左右子树:获取左右子树的查找结果。
- 判断LCA:若左右子树均找到节点,当前节点为LCA;否则返回非空结果。
解决代码
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null){return null;}if(root == p || root == q){//递归返回条件,找到p 获 qreturn root;}TreeNode left = lowestCommonAncestor(root.left, p, q);//对左子树递归TreeNode right = lowestCommonAncestor(root.right, p, q);//对右子树递归if(left != null && right != null){//找到两个节点return root;}else if(left != null && right == null){//只找到一个节点return left;}else if(left == null && right != null){return right;}else{//没找到节点return null;}}
}