代码随想录算法训练营二十一天 | 530.二叉搜索树的最小绝对差 501.二叉搜索树中的众数 236. 二叉树的最近公共祖先
530.二叉搜索树的最小绝对差
class Solution {
TreeNode node = null;
int min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return 0;
}
test(root);
return min;
}
public int test(TreeNode root) {
if (root == null) {
return min;
}
int min1 = test(root.left);
if (node != null && Math.abs(node.val - root.val) < min) {
min = Math.abs(node.val - root.val);
}
node = root;
int min2 = test(root.right);
min = min1 < min2 ? min1 : min2;
return min;
}
}
501.二叉搜索树中的众数
class Solution {
private int maxNum = 0;
private int num = 0;
private TreeNode node = null;
public int[] findMode(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null) {
return result.stream().mapToInt(i->i).toArray();
}
test(root, result);
return result.stream().mapToInt(i->i).toArray();
}
public void test (TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
test(root.left, result);
if (node == null) {
num++;
} else if (node.val == root.val) {
num++;
} else {
num = 1;
}
node = root;
if (num == maxNum) {
result.add(root.val);
}
if (num > maxNum) {
maxNum = num;
result.clear();
result.add(root.val);
}
test(root.right, result);
}
}
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) {
return root;
}
if (left != null && right == null) {
return left;
} else if (left == null && right != null) {
return right;
} else {
return null;
}
}
}