二叉搜索树的最小绝对差、二叉树的所有路径、左叶子之和
二叉搜索树的最小绝对差
力扣连接:530. 二叉搜索树的最小绝对差(简单)
1.递归的方法
递归的图解步骤
关键点:
- 需要用一个pre节点记录一下cur节点的前一个节点。
递归代码
// 递归法
class Solution {
TreeNode pre; //记录前一个节点
Integer min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
getMinimum(root);
return min;
}
public void getMinimum(TreeNode cur) {
if(cur==null) return;
getMinimumDifference(cur.left);
if(pre!=null){
min = Math.min(min, cur.val-pre.val);
}
pre = cur;
getMinimumDifference(cur.right);
}
}
二叉搜索树中的众数
力扣连接:501.二叉搜索树中的众数(简单)
1.递归的方法
既然是搜索树,它中序遍历就是有序的。
递归的图解步骤
关键点:
- 需要用一个pre节点记录一下cur节点的前一个节点。
- 当 count > maxCount 时,清空列表,再加入节点值
递归代码
class Solution {
int count = 0;
int maxCount = 0;
TreeNode pre; //记录前一个节点
List<Integer> result = new ArrayList<>();
public int[] findMode(TreeNode root) {
searchMax(root);
return result.stream().mapToInt(Integer::valueOf).toArray();
}
public void searchMax(TreeNode cur){
if(cur==null) return;
searchMax(cur.left);
if(pre==null||cur.val!=pre.val){
count = 1;
}else{
count++;
}
if(count>maxCount){
maxCount = count;
result.clear();
result.add(cur.val);
}else if(count==maxCount){
result.add(cur.val);
}
pre = cur;
searchMax(cur.right);
}
}
二叉树的最近公共祖先
力扣连接:236. 二叉树的最近公共祖先(简单)
能自底向上查找就可以找到公共祖先了
二叉树回溯的过程就是从低到上。
后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。
图解步骤
代码
class Solution {
//后序遍历
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q) return root;
TreeNode leftNode = lowestCommonAncestor(root.left, p, q); //左
TreeNode rightNode = lowestCommonAncestor(root.right, p, q); //右
//中
if(leftNode==null && rightNode!=null){
return rightNode;
}else if(leftNode!=null && rightNode==null){
return leftNode;
}else if(leftNode==null && rightNode==null){
return null;
}else{
return root;
}
}
}