代码随想录算法训练营第二十一天| 530 二叉搜索树的最小绝对差 501 二叉搜索树的众数 236 二叉树的最近公共祖先
目录
530 二叉搜索树的最小绝对差
利用二叉搜索树的性质,对树进行中序遍历,过程中统计差值。
class Solution {
int res = Integer.MAX_VALUE;
TreeNode pre;
public int getMinimumDifference(TreeNode root) {
dfs(root);
return res;
}
private void dfs(TreeNode cur){//中序遍历
if(cur == null)return;
dfs(cur.left);//左
if(pre != null)res = Math.min(res,cur.val - pre.val);//中
pre = cur;
dfs(cur.right);//右
}
}
时间复杂度O(n)
空间复杂度O(n)
501 二叉搜索树的众数
利用二叉搜索树的性质,对树进行中序遍历,由于是有序的所以有如下三种情况:
- 统计完一个值的出现次数之后如果遇到了出现次数更多的值,将这个值清除后加入下一个值到resList。
- 如果二者出现次数相同则保留原来值并且加入下一个值。
- 如果下一个值小于之前值则不做处理。
class Solution {
int count;
int maxCount;
List<Integer>resList;
TreeNode pre;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxCount = -1;
count = 0;
pre = null;
dfs(root);
int res[] = new int[resList.size()];
for(int i = 0;i < res.length;i++){
res[i] = resList.get(i);
}
return res;
}
void dfs(TreeNode root){
if(root == null)return;
dfs(root.left);
if(pre == null || pre.val != root.val){
count = 1;
}else{
count++;
}
if(count > maxCount){
resList.clear();
resList.add(root.val);
maxCount = count;
}else if(count == maxCount)resList.add(root.val);
pre = root;
dfs(root.right);
}
}
时间复杂度O(n)
空间复杂度O(n)
236 二叉树的最近公共祖先
后序遍历二叉树,如果遍历到q或p或null节点就返回,如果没有则继续递归遍历左子树和右子树,并用l和r存储遍历结果。
此时有如下四种情况:
- l找到p或q,r未找到。返回l
- r找到p或q,l未找到,返回r
- l与r都没找到p或q,则返回null
- l找到了p或者q,r找到了剩下的一个,则该节点为最近公共祖先节点,返回该节点
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == q || root == p)return root;
//后序遍历 左右中
TreeNode l = lowestCommonAncestor(root.left,p,q);
TreeNode r = lowestCommonAncestor(root.right,p,q);
if(l == null && r == null)return null;
else if(l == null && r != null)return r;
else if(l != null && r == null)return l;
else return root;
}
}
时间复杂度O(n)
空间复杂度O(n)