代码随想录算法训练营第二十一天 | 530.二叉搜索树的最小绝对差 、 501.二叉搜索树中的众数、 236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
递归中序遍历,维护一个min_value
注意min_value初始化为Integer.MAX_VALUE
class Solution {
int min_value;
int pre;
boolean start = true;
public int getMinimumDifference(TreeNode root) {
min_value = Integer.MAX_VALUE;
dfs(root);
return min_value;
}
void dfs(TreeNode node) {
if(node == null) return;
dfs(node.left);
if(start) {
pre = node.val;
start = false;
} else {
min_value = Math.min(min_value, Math.abs(pre - node.val));
pre = node.val;
}
dfs(node.right);
}
}
501.二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
这里要维护一个max_count
class Solution {
TreeNode pre;
ArrayList<Integer> list;
int count;
int maxCount;
public int[] findMode(TreeNode root) {
pre = null;
count = 0;
maxCount = 0;
list = new ArrayList<>();
dfs(root);
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); ++i) {
res[i] = list.get(i);
}
return res;
}
void dfs(TreeNode node) {
if(node == null) return;
dfs(node.left);
// 若遍历到第一个元素或者pre != node, 重新设置count = 1
if(pre == null || pre.val != node.val) {
count = 1;
} else {
// 否则count++
count++;
}
// 更新pre
pre = node;
if(count > maxCount) {
// 一旦有新的max出现,清空当前list
maxCount = count;
list.clear();
list.add(node.val);
} else if (count == maxCount) {
list.add(node.val);
}
dfs(node.right);
}
}
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
后序遍历,新鲜,多熟悉熟悉
class Solution {
// 回溯
// 1. 确定递归参数和返回值
// 参数:两个节点,当前遍历到的节点
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 2. 确定递归的终止条件
if (root == null || root == p || root == q) { // 递归结束条件
// 首先找到p或q,就return p 或 q
return root;
}
// 后序遍历
TreeNode left = lowestCommonAncestor(root.left, p, q); // 左
TreeNode right = lowestCommonAncestor(root.right, p, q); // 右
if(left == null && right == null) { // 若未找到节点 p 或 q
return null;
}else if(left == null && right != null) { // 若在右子树找到节点
return right; // 回溯
}else if(left != null && right == null) { // 若在左子树找到节点
return left; // 回溯
}else { // 若找到两个节点在左右子树中,说明root是最近公共节点
return root;
}
}
}