随想录训练营Day21 | 第六章 二叉树 part07 530.二叉搜索树的最小绝对差,501. 二叉搜索树中的众数
标签: LeetCode闯关记
530.二叉搜索树的最小绝对差
思路:
- 二叉搜索树上求最值,求差值,思考二叉搜索树的有序性
- 用中序遍历,想象成一个递增的有序数组
- 用pre来记录遍历的前一个节点
class Solution {
TreeNode pre = null;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root == null){
return 0;
}
getMinimumDifference(root.left);
if(pre != null){
res = Math.min(res, root.val - pre.val);
}
pre = root;
getMinimumDifference(root.right);
return res;
}
}
501. 二叉搜索树中的众数
class Solution {
int count;
int maxCount;
TreeNode pre;
ArrayList<Integer> resList;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
count = 0;
maxCount = Integer.MIN_VALUE;
pre = null;
find(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
public void find(TreeNode root){
if(root == null){
return;
}
find(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;
find(root.right);
}
}