代码随想录算法训练营day21 | leetcode ● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● ***236. 二叉树的最近公共祖先

2023-05-28,,

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

分析1.0

二叉搜索树,中序遍历形成一个升序数组,节点差最小值一定在中序遍历两个相邻节点产生

✡✡✡ 即 双指针思想在树遍历中的应用

class Solution {
TreeNode pre;// 记录上一个遍历的结点
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root==null)return 0;
traversal(root);
return result;
}
public void traversal(TreeNode root){
if(root==null)return;
//左
traversal(root.left);
//中
if(pre!=null){
result = Math.min(result,root.val-pre.val);
}
pre = root;
//右
traversal(root.right);
}
}

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

分析1.0

在修改了定义的二叉搜索树中找元素出现最多的节点值并返回那个值

遍历 采用Map<节点值,节点个数>, 再遍历一次取value最大值

分析2.0

借助搜索特性 统计每个相同val节点个数

if (pre == NULL) { // 第一个节点
count = 1; // 频率为1
} else if (pre->val == cur->val) { // 与前一个节点数值相同
count++;
} else { // 与前一个节点数值不同
count = 1;
}
pre = cur; // 更新上一个节点
class Solution {
ArrayList<Integer> resList;
int maxCount;
int count;
TreeNode pre; public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
findMode1(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
} public void findMode1(TreeNode root) {
if (root == null) {
return;
}
findMode1(root.left); int rootValue = root.val;
// 计数
if (pre == null || rootValue != pre.val) {
count = 1;
} else {
count++;
}
// 更新结果以及maxCount
if (count > maxCount) {
resList.clear();
resList.add(rootValue);
maxCount = count;
} else if (count == maxCount) {
resList.add(rootValue);
}
pre = root; findMode1(root.right);
}
}

LeetCode 二叉树的最近公共祖先

分析1.0

向上传递的是包含 p 或 p 或 p和q的共同根节点

class Solution {
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) { // 若未找到节点 p 或 q
return null;
}else if(left == null && right != null) { // 若找到一个节点
return right;
}else if(left != null && right == null) { // 若找到一个节点
return left;
}else { // 若找到两个节点
return root;
}
}
}

总结

    搜索一条边的写法:

    if (递归函数(root->left)) return ;
    
    if (递归函数(root->right)) return ;

    搜索整个树写法:

    left = 递归函数(root->left);  // 左
    right = 递归函数(root->right); // 右
    left与right的逻辑处理; // 中

常用变量名增量更新

size、val、ans、cnt、cur、pre、next、left、right、index、gap、tar、res、src、len、start、end、flag、ch

代码随想录算法训练营day21 | leetcode ● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● ***236. 二叉树的最近公共祖先的相关教程结束。

《代码随想录算法训练营day21 | leetcode ● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● ***236. 二叉树的最近公共祖先.doc》

下载本文的Word格式文档,以方便收藏与打印。