530 二叉搜索树的最小绝对差
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/ 中序遍历记录pre值
class Solution {
public int getMinimumDifference(TreeNode root) {
Integer pre = null;
int globalMin = Integer.MAX_VALUE;
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.offerFirst(root);
root = root.left;
} else {
root = stack.pollFirst();
if (pre != null) globalMin = Math.min(globalMin, Math.abs(pre - root.val));
pre = root.val;
root = root.right;
}
}
return globalMin;
}
}
501 二叉搜索树中的众数
https://leetcode.cn/problems/find-mode-in-binary-search-tree/ 中序遍历记录pre数的count并及时更新count最大值和该值对应得数字得集合。
class Solution {
public int[] findMode(TreeNode root) {
TreeNode pre = null;
int count = 0;
int maxCount = 0;
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.offerFirst(root);
root = root.left;
} else {
root = stack.pollFirst();
if (pre == null || pre.val != root.val) {
count = 1;
} else {
count++;
}
if (count > maxCount) {
result.clear();
result.add(root.val);
maxCount = count;
} else if (count == maxCount) {
result.add(root.val);
}
pre = root;
root = root.right;
}
}
int[] array = new int[result.size()];
for (int i = 0; i < array.length; i++) {
array[i] = result.get(i);
}
return array;
}
}
236 二叉树的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
后序遍历,base case是 null或者p或者q时返回本身,只有当左右返回都不为0时说明pq在左右各分了一个,该根为LAC,否则返回非null的子问题解(可以是一个node,null/p/q,也可以是已经找到的LAC)。
值得注意的是,由于保证了pq都在树里,如果p是q的祖先,遇到 p时直接返回p,至此再不会遇到q, 整棵树的返回值为p,也是答案要的LCA。
class Solution { // TO(n) SO(h)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode leftResult = lowestCommonAncestor(root.left, p, q);
TreeNode rightResult = lowestCommonAncestor(root.right, p, q);
if (leftResult == null) return rightResult;
if (rightResult == null) return leftResult;
return root;
}
}