530.二叉搜索树的最小绝对差
利用二叉树性质,(中序遍历有序)使用双指针计算最小绝对差
迭代法二叉树遍历需要熟悉
501.二叉搜索树中的众数
class Solution {
ArrayList<Integer> resList;
int maxCount;
int count;
TreeNode pre;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
findMode1(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
public void findMode1(TreeNode root) {
if (root == null) {
return;
}
findMode1(root.left);
int rootValue = root.val;
// 计数
if (pre == null || rootValue != pre.val) {
count = 1;
} else {
count++;
}
// 更新结果以及maxCount
if (count > maxCount) {
resList.clear();
resList.add(rootValue);
maxCount = count;
} else if (count == maxCount) {
resList.add(rootValue);
}
pre = root;
findMode1(root.right);
}
}
要点:
1. 每次超过了最大值需要清空链表: list.clear()
2. count>max的更新需要在count==max添加结果之后,或者独立出来(if+else if)否则先让max=count,再去判断如果想等就加入,会有冗余的结果
236. 二叉树的最近公共祖先
注意题目条件:一定存在,且每个数字unique
所以遇到p/q就直接返回(因为pq一定存在且唯一)
图片来源:代码随想录
此题需要在后续位置处理左右子树返回值,所以其实遍历的整颗树,并不是遍历边
上图第三点:返回的是pq第一次出现的节点,传上去为了找到最近公共祖先(该节点左右皆为非空)此种情况为情况一(最近公共祖先不是pq节点本身)。 但是情况1已经包含了情况2(pq为最近公共祖先)遇到p,q就直接返回,然后一直通过途中第三点的情况(公共祖先那边非空,另一边为空,所以上传公共祖先这边的返回值)上传到根节点,返回为最终结果。