530.二叉搜索树的最小绝对差
完成
代码
二叉排序树使用中序遍历时是有序的。
class Solution {
public List<Integer> list = new ArrayList<>();
public void inOrder(TreeNode node){
if(node == null) return;
inOrder(node.left);
list.add(node.val);
inOrder(node.right);
}
public int getMinimumDifference(TreeNode root) {
inOrder(root);
int res = Math.abs(list.get(0) - list.get(1));
for (int i = 2; i < list.size(); i++) {
int temp = Math.abs(list.get(i) - list.get(i-1));
if(res>temp) res = temp;
}
return res;
}
}
501.二叉搜索树中的众数
完成
代码
暴力法
public int[] findMode(TreeNode root) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
if (root == null) return list.stream().mapToInt(Integer::intValue).toArray();
// 获得频率 Map
searchBST(root, map);
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream()
.sorted((c1, c2) -> c2.getValue().compareTo(c1.getValue()))
.collect(Collectors.toList());
list.add(mapList.get(0).getKey());
// 把频率最高的加入 list
for (int i = 1; i < mapList.size(); i++) {
if (mapList.get(i).getValue() == mapList.get(i - 1).getValue()) {
list.add(mapList.get(i).getKey());
} else {
break;
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
void searchBST(TreeNode curr, Map<Integer, Integer> map) {
if (curr == null) return;
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
searchBST(curr.left, map);
searchBST(curr.right, map);
}
236. 二叉树的最近公共祖先
完成
代码
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == p || root == q || root == null) 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;
}
}
}