题目链接:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
文章讲解:https://programmercarl.com/0530.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E7%BB%9D%E5%AF%B9%E5%B7%AE.html
视频讲解:https://www.bilibili.com/video/BV1DD4y11779
class Solution {
TreeNode pre;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
getMin(root);
return res;
}
public void getMin(TreeNode node) {
if (node == null) {
return;
}
getMin(node.left);
if (pre != null) {
res = Math.min(res, Math.abs(node.val - pre.val));
}
pre = node;
getMin(node.right);
}
}
题目链接:https://leetcode.cn/problems/find-mode-in-binary-search-tree/
文章讲解:https://programmercarl.com/0501.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E4%BC%97%E6%95%B0.html
视频讲解:https://www.bilibili.com/video/BV1fD4y117gp
class Solution {
int times = 0;
int maxTimes = 0;
TreeNode pre;
List<Integer> res = new ArrayList<Integer>();
public int[] findMode(TreeNode root) {
findRes(root);
int[] resArr = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
resArr[i] = res.get(i);
}
return resArr;
}
// 中序遍历:左中右
public void findRes(TreeNode node) {
if (node == null) {
return;
}
findRes(node.left);
if (pre == null || pre.val != node.val) {
times = 1;
}
if (pre != null && pre.val == node.val) {
times++;
}
if (times > maxTimes) {
maxTimes = times;
res.clear();
res.add(node.val);
} else if (times == maxTimes) {
res.add(node.val);
}
pre = node;
findRes(node.right);
}
}
题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
文章讲解:https://programmercarl.com/0236.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88.html
视频讲解:https://www.bilibili.com/video/BV1jd4y1B7E2
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(left==null){
return right;
}
if(right==null){
return left;
}
return root;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容