530.二叉搜索树的最小绝对差
🔗题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
💡解题思路:递归
设置双指针,定义一个变量存放最小绝对差
代码如下:
int min = Integer.MAX_VALUE;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
getMinNum(root);
return min;
}
private void getMinNum(TreeNode root) {
if(root == null) return;
//左
getMinNum(root.left);
//中
if(pre != null){
min = Math.min(min, Math.abs(root.val - pre.val));
}
pre = root;
//右
if (root.right != null) {
getMinNum(root.right);
}
}
501.二叉搜索树中的众数
🔗题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
💡解题思路:递归
遍历有序数组的元素出现频率,从头遍历,那么一定是相邻两个元素作比较,然后就把出现频率最高的元素输出就可以了。频率count 大于 maxCount的时候,不仅要更新maxCount,而且要清空结果集(以下代码为result数组),因为结果集之前的元素都失效了。
代码如下:
int maxNum;
int count;
TreeNode pre;
ArrayList<Integer> resList;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxNum = 0;
count = 0;
pre = null;
traversal(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
private void traversal(TreeNode root) {
if (root == null) return;
//左
traversal(root.left);
int rootValue = root.val;
//计数
if (pre == null || rootValue != pre.val) {
count = 1;
} else {
count++;
}
if (count > maxNum) {
resList.clear();
resList.add(rootValue);
maxNum = count;
} else if (count == maxNum) {
resList.add(rootValue);
}
pre = root;
traversal(root.right);
}
236. 二叉树的最近公共祖先
🔗题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
💡解题思路:递归
递归三部曲:
- 确定递归函数返回值以及参数
需要递归函数返回值,来告诉我们是否找到节点q或者p,那么返回值为bool类型就可以了。
但我们还要返回最近公共节点,可以利用上题目中返回值是TreeNode * ,那么如果遇到p或者q,就把q或者p返回,返回值不为空,就说明找到了q或者p。
- 确定终止条件
遇到空的话,因为树都是空了,所以返回空。
那么我们来说一说,如果 root == q,或者 root == p,说明找到 q p ,则将其返回,这个返回值,后面在中节点的处理过程中会用到,那么中节点的处理逻辑,下面讲解。
- 确定单层递归逻辑
在递归函数有返回值的情况下:如果要搜索一条边,递归函数返回值不为空的时候,立刻返回,如果搜索整个树,直接用一个变量left、right接住返回值,这个left、right后序还有逻辑处理的需要,也就是后序遍历中处理中间节点的逻辑(也是回溯)。
代码如下:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
//后序遍历
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null && right == null) {
return null;
} else if (left == null && right != null) {
return right;
} else if (left != null && right == null) {
return left;
} else {
return root;
}
}