二叉搜索树中序遍历得到的值序列是递增有序的
利用好这个特性!
530.二叉搜索树的最小绝对差
题目链接/文章讲解:代码随想录
视频讲解:二叉搜索树中,需要掌握如何双指针遍历!| LeetCode:530.二叉搜索树的最小绝对差_哔哩哔哩_bilibili
class Solution {
TreeNode pre;
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return 0;
}
helper(root);
return result;
}
public void helper(TreeNode root) {
if (root == null) {
return;
}
helper(root.left);
if (pre != null) {
result = Math.min(result, root.val - pre.val);
}
pre = root;
helper(root.right);
}
}
501.二叉搜索树中的众数
视频讲解:不仅双指针,还有代码技巧可以惊艳到你! | LeetCode:501.二叉搜索树中的众数_哔哩哔哩_bilibili
class Solution {
ArrayList<Integer> list;
TreeNode pre;
int count;
int maxCount;
public int[] findMode(TreeNode root) {
list = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
helper(root);
int ans[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
ans[i] = list.get(i);
}
return ans;
}
public void helper(TreeNode root) {
if (root == null) {
return;
}
helper(root.left);
if (pre == null || pre.val != root.val) {
count = 1;
} else {
count++;
}
if (count > maxCount) {
list.clear();
list.add(root.val);
maxCount = count;
} else if (count == maxCount) {
list.add(root.val);
}
pre = root;
helper(root.right);
}
}
236. 二叉树的最近公共祖先
视频讲解:自底向上查找,有点难度! | LeetCode:236. 二叉树的最近公共祖先_哔哩哔哩_bilibili
想要从下往上处理一定是后序遍历,如果在递归中找到了p或者q就不需要继续寻找了,因为此时就是最近公共祖先。
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) {
// 若未找到节点 p 或 q
return null;
} else if (left == null && right != null) {
// 若找到一个节点
return right;
} else if (left != null && right == null) {
// 若找到一个节点
return left;
} else { // 若找到两个节点
return root;
}
}
}