持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第12天,点击查看活动详情🚀🚀
前言
今天的题目非常非常适合自己,就是都是属于那种踮起脚尖就够的着的。 为卡哥的选题打call!!!
530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
递归
var getMinimumDifference = function (root) {
let arr = [];
const dfs = (root) => {
if(!root) return
dfs(root.left);
arr.push(root.val);
dfs(root.right)
}
dfs(root);
let diff = 9999999;
for(let i = 0;i < arr.length;i++){
for(let j = i+1;j < arr.length;j++){
if(arr[j] - arr[i] < diff)
diff = arr[j] - arr[i];
}
}
return diff
};
看到二叉搜索树,就应该直接条件反想到用中序遍历得到一个有序数组,后面自然而然就有思路了~
501. 二叉搜索树中的众数 - 力扣(LeetCode)
递归
var findMode = function(root) {
let arr = [];
const dfs = (root) => {
if(!root) return
dfs(root.left);
arr.push(root.val);
dfs(root.right);
}
dfs(root);
let map = new Map();
for(let i = 0;i < arr.length;i++){
map.set(arr[i], map.get(arr[i])+ 1 || 1);
}
let res = []
let max = 0;
for(let [key,val] of map){
if(val == max){
res.push(key)
}
if(val > max){
res = [];
max = val;
res.push(key)
}
}
return res
};
难点
- 二叉搜索树 == 中序遍历 !!!
- 将数组转换成map
for(let i = 0;i<arr.length;i++){
map.set(arr[i],map.get(arr[i])+ 1|| 1)
}
- 取map中的众数
主要考虑到众数不止一个数,所以在这里自己踩了点坑
for(let [key,val] of map){
if(val == max){
res.push(key)
}
if(val > max){
res = [];
max = val;
res.push(key)
}
}
236. 二叉树的最近公共祖先 - 力扣(LeetCode)
递归
var lowestCommonAncestor = function(root, p, q) {
if(!root) return root;
const dfs = (root,p,q) => {
if(!root) return null;
if(root == p || root == q) return root;
root.left = dfs(root.left,p,q)
root.right = dfs(root.right,p,q)
if(root.left && root.right) return root;
if(!root.left && root.right) return root.right;
if(root.left && !root.right) return root.left;
else{
return null
}
}
return dfs(root,p,q);
};
难点
这个题看了一下卡哥的视频,思路还是一如既往的清晰。 难点就是如何把值传递上去的过程了。