代码随想录算法训练营第第21天 | 530.二叉搜索树的最小绝对差 、501.二叉搜索树中的众数 、236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
需要领悟一下二叉树遍历上双指针操作,优先掌握递归
题目链接/文章讲解:https://programmercarl.com/0530.二叉搜索树的最小绝对差.html
视频讲解:https://www.bilibili.com/video/BV1DD4y11779
var getMinimumDifference = function(root) {
let preVal = null;
let minVal = Infinity;
const traverse = (node) => {
if (node === null) return;
let left;
if (node.left) {
traverse(node.left);
}
if (preVal!==null && (node.val - preVal) < minVal) {
minVal = node.val -preVal;
}
preVal = node.val;
traverse(node.right);
}
traverse(root);
return minVal;
};
501.二叉搜索树中的众数
和 530差不多双指针思路,不过 这里涉及到一个很巧妙的代码技巧。
可以先自己做做看,然后看我的视频讲解。
https://programmercarl.com/0501.二叉搜索树中的众数.html
视频讲解:https://www.bilibili.com/video/BV1fD4y117gp
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findMode = function(root) {
let maxCount = 1;
let curCount = 0;
let prev = root;
let res = [];
const traverse =(node)=>{
if (node === null) return;
traverse(node.left);
if (prev.val === node.val){
curCount++;
}else {
curCount = 1;
}
prev = node;
if (maxCount === curCount) {
res.push(node.val);
} else if (maxCount <curCount) {
res = [];
maxCount = curCount;
res.push(node.val)
} else {
}
traverse(node.right);
}
traverse(root);
return res;
};
- 二叉树的最近公共祖先
本题其实是比较难的,可以先看我的视频讲解
https://programmercarl.com/0236.二叉树的最近公共祖先.html
视频讲解:https://www.bilibili.com/video/BV1jd4y1B7E2
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if (root === q || root === p || root === null) return root;
let left = lowestCommonAncestor(root.left, p, q);
let right = lowestCommonAncestor(root.right, p, q);
if (left !== null && right === null) {
return left;
} else if (left === null && right !== null) {
return right;
} else if (left !== null && right !== null) {
return root;
} else {
return null;
}
};