530.二叉搜索树的最小绝对差
思路:二叉搜索树的中序遍历是有序的。理解这句话,然后根据二叉搜索树的这个特性来做这道题。
class Solution {
// 同样利用二叉树中序遍历是一个有序数组。
private List<Integer> list = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
int min = Integer.MAX_VALUE;
inorder(root);
for (int i = 0; i < list.size() - 1; i++) {
int temp = list.get(i + 1) - list.get(i);
if (temp < min) min = temp;
}
return min;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
list.add(node.val);
inorder(node.right);
}
}
501.二叉搜索树中的众数
思路:同样利用二叉搜索树的特性(二叉搜索树中序遍历是一个有序数组)。中序递归遍历,如果当前节点与前一个节点值相同,则记录count的值,如果count的值大于或者等于最大相同节点个数,就要更新结果。
class Solution {
List<Integer> list = new ArrayList<>();
int count; // 记录相同节点个数
int maxCount; // 记录最大相同节点个数
TreeNode pre = null; // 指向前一个节点
public int[] findMode(TreeNode root) {
inorder(root);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
if (pre == null || pre.val != node.val) { // 如果是第一个节点,或者当前节点于前一个节点值不同
count = 1;
} else {
count++;
}
// 跟新结果
if (count > maxCount) {
list.clear();
list.add(node.val);
maxCount = count;
} else if (count == maxCount) {
list.add(node.val);
}
pre = node;
inorder(node.right);
}
}
236. 二叉树的最近公共祖先
思路:通过后序递归遍历(应为要从下往上返回,所以要采用后序遍历的顺序),找到了p节点或者q节点,就将节点向上返回,如果没有找到,就返回null。如果一个节点的遍历左子树和右子树时都返回了节点,说明这个节点就是父节点,则将当前节点返回。
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 && right == null) { // 都没找到返回null
return null;
} else if (left != null && right == null) { // 只有左边有,反作左边传上来的值。
return left;
} else if (left == null && right != null) {
return right;
} else { // 左右都找到了返回当前节点
return root;
}
}
}