Day21题目
LeetCode530.二叉搜索树的最小绝对值差
核心思想:想要获取最小绝对值差,只需要中序遍历的时候维护前一个节点。计算这两个节点的差值的绝对值。维护一个最小值最为最终答案。
class Solution {
int res = Integer.MAX_VALUE;
int pre = 0;
public int getMinimumDifference(TreeNode root) {
// 中序
pre = root.val;
help(root);
return res;
}
public void help(TreeNode root){
if(root == null) return;
help(root.left);
int sub =Math.abs(root.val - pre);
if(sub > 0&& sub < res){
res = sub;
}
pre = root.val;
help(root.right);
}
}
LeetCode501.获取二叉搜索树的众数:得到树中个数最多的元素
核心思想:可以使用pre记录上一个遍历到的元素,使用count记录这个元素目前的个数,再用一个maxCount记录目前最多的个数,如果一个元素count=maxcout那就加入众数,大于maxcount就把返回列表清空再加入这个元素。
class Solution {
int count = 1;
int maxCount = 0;
TreeNode pre = null;
List<Integer> res = new ArrayList<>();
public int[] findMode(TreeNode root) {
// 中序遍历,如果pre 与root.val值相同,则count +1
help(root);
// 构造结果
int[] arr = new int[res.size()];
for(int i = 0 ; i < res.size(); i ++){
arr[i] = res.get(i);
}
return arr;
}
public void help(TreeNode root){
if(root == null) return;
help(root.left);
if(pre == null){
// 第一个元素的时候pre为null,这时候cur元素个数为1
count = 1;
}else if(pre.val == root.val){
// 如果pre和root元素值相同,则count++
count ++;
} else{
// 不同的时候pre这个元素的个数重置为1
count = 1;
}
if(count == maxCount){
// 如果个数等于目前最大个数,加入到结果集
res.add(root.val);
}
// 如果大于最大个数
if(count > maxCount){
// 清除结果集
res.clear();
// 加入这个元素
res.add(root.val);
// 更新最大个数
maxCount = count;
}
// 更新pre
pre = root;
help(root.right);
}
}
LeetCode236.二叉树的最近公共祖先:返回包含所给两个节点的最近父节点
核心思想:遍历这个二叉树,第一个左右子树分别有这个两个节点的节点就是最近的。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(root == p || root == q ) return root;
// 遍历它的子节点,得到返回值,可能是null,可能是找到的值
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left == null && right == null){
// 如果都是null,说明这个子树没有包含p或者q
return null;
}else if(left == null){
// 如果包含了q就返回q
return right;
}else if(right == null){
// 包含了p就返回p
return left;
}else{
// 包含了两个就返回这个节点。这个节点是最近的节点。
return root;
}
}
}
345



被折叠的 条评论
为什么被折叠?



