530.二叉搜索树的最小绝对差
题目链接:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
class Solution {
int pre;
int ans;
public int getMinimumDifference(TreeNode root) {
pre = -1;
ans = Integer.MAX_VALUE;
inorder(root);
return ans;
}
private void inorder(TreeNode root) {
if(root == null) {
return;
}
inorder(root.left);
if(pre == -1) {
pre = root.val;
}else {
ans = ans > root.val - pre ? root.val - pre : ans;
pre = root.val;
}
inorder(root.right);
}
}
501.二叉搜索树中的众数
题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)
class Solution {
int num = 1;
int k = 0;
int val;
public int[] findMode(TreeNode root) {
Map<Integer,Integer> map = new HashMap<>();
val = root.val;
inorder(root, map);
int[] ans = new int[map.size()];
int j = 0;
for(int i : map.keySet()) {
ans[j++] = i;
}
return ans;
}
private void inorder(TreeNode root,Map<Integer,Integer> map) {
if(root == null) {
return;
}
inorder(root.left,map);
if(val == root.val) {
++k;
if(k == num) {
map.put(root.val, k);
}else if(k > num){
map.clear();
map.put(root.val, k);
num = k;
}
}else {
val = root.val;
k = 1;
if(k == num) {
map.put(root.val, k);
}
}
inorder(root.right, map);
}
}
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(right == null) return left;
if(left == null) return right;
return root;
}
}