LeetCode 530 二叉搜索树的最小绝对差
题目链接:530.二叉树搜索树的最小绝对差
java
class Solution {
int min = Integer.MAX_VALUE;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
traversal(root);
return min;
}
public void traversal(TreeNode root){
if(root == null) return;
traversal(root.left);
if(pre != null && (root.val - pre.val) < min){
min = root.val - pre.val;
}
pre = root;
traversal(root.right);
}
}
LeetCode 501 二叉搜索树中的众数
题目链接:501.二叉搜索树中的众数
java
class Solution {
TreeNode pre;
int maxTimes = 1;
int currentTimes;
List<Integer> list = new ArrayList<>();
public int[] findMode(TreeNode root) {
if(root == null) return new int[]{};
traversal(root);
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++){
res[i] = list.get(i);
}
return res;
}
public void traversal(TreeNode root){
if(root == null) return;
traversal(root.left);
if(pre == null || root.val != pre.val){
currentTimes = 1;
}
if(pre != null && root.val == pre.val){
currentTimes+=1;
}
if(currentTimes > maxTimes){
list.clear();
maxTimes = currentTimes;
list.add(root.val);
}else if(currentTimes == maxTimes){
list.add(root.val);
}
pre = root;
traversal(root.right);
}
}
LeetCode 236 二叉树的最近公共祖先
题目链接:236.二叉树的最近公共祖先
java
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(root.val == p.val || root.val == q.val) 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 right;
if(left != null && right == null) return left;
return null;
}
}