力扣 530.二叉搜索树的最小绝对差
class Solution {
List<Integer> inorderList = new ArrayList<>();
public void inorder(TreeNode root) {
if(root == null) return;
if(root.left != null) inorder(root.left);
inorderList.add(root.val);
if(root.right != null) inorder(root.right);
}
public int getMinimumDifference(TreeNode root) {
inorder(root);
int minValue = Integer.MAX_VALUE;
for(int i = inorderList.size() - 1; i > 0; i--) {
int value = inorderList.get(i) - inorderList.get(i - 1);
if(value < minValue) {
minValue = value;
}
}
return minValue;
}
}
力扣501.二叉搜索树中的众数
class Solution {
TreeNode pre = new TreeNode();
List<Integer> resList = new ArrayList<>();
int count;
int maxCount;
public int[] findMode(TreeNode root) {
pre = null;
count = 0;
maxCount = 0;
inorder(root);
int[] resArray = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
resArray[i] = resList.get(i);
}
return resArray;
}
public void inorder(TreeNode root) {
if (root == null)
return;
if (root.left != null)
inorder(root.left);
if (pre == null || pre.val != root.val)
count = 1;
else
count++;
if (count > maxCount) {
resList.clear();
maxCount = count;
resList.add(root.val);
} else if (count == maxCount) {
resList.add(root.val);
}
pre = root;
if (root.right != null)
inorder(root.right);
}
}
力扣236. 二叉树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left == null && right == null) return null;
else if(left != null && right == null) return left;
else if(left == null && right != null) return right;
return root;
}
}