1. 二叉搜索树的最小绝对差
530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
pre指针指向前一个节点
注意一开始pre是null(可以理解为最左节点的左孩子null)
class Solution {
TreeNode pre = null;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
deal(root);
return res;
}
public void deal(TreeNode root){
if(root == null) return ;
deal(root.left);
if(pre != null)
res = Math.min(res, root.val - pre.val);
pre = root;
deal(root.right);
}
}
2. 二叉搜索树中的众数
当pre的值等于cur的值,count++, 否则重置为1
当count == max时,直接向res里添加当前值
如果,count > max,说明当前值的数量是所有遍历过的元素中最多的
此时,max=count,并清空res,添加当前值
class Solution {
int max;
int count;
ArrayList<Integer> res;
TreeNode pre;
public int[] findMode(TreeNode root) {
res = new ArrayList<>();
deal(root);
int[] temp = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
temp[i] = res.get(i);
}
return temp;
}
public void deal(TreeNode root) {
if(root == null) return;
deal(root.left);
if(pre == null || root.val != pre.val)
count = 1;
else
count++;
if(count > max){
max = count;
res.clear();
res.add(root.val);
}else if(count == max){
res.add(root.val);
}
pre = root;
deal(root.right);
}
}
3. 二叉树的最近公共祖先
236. 二叉树的最近公共祖先 - 力扣(LeetCode)
当前节点等于pq其中一个,即可返回当前节点
遍历左右子树,将其结果返回给上一层的中间节点
中间节点,判断左右子树的返回情况
左右子树中pq都找到了,则返回当前节点
找到其中一个,返回找到的节点
都没找到返回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) return root;
if(left != null) return left;
if(right != null) return right;
return null;
}
}
情况1:pq不在同一个子树,按照上面的步骤很清晰
情况2:pq在同一个子树(p或者q作为子树的根,另一个在它的子树中),
那么在向下的过程中,可以直接返回这个root,不用向下再遍历了,即第一行判断
如果是情况2,那么另一个元素一定在这个root下,这个root就是最近公共祖先
不是情况2,则恢复到情况1的步骤,继续比较左右子树