二叉树part6

二叉树part6

530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)

因为二叉搜索树BST中序遍历是升序序列,所以利用这个性质

class Solution {

    int diff = Integer.MAX_VALUE;

    TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {
        preOrder(root);
        return diff;
    }

    public void preOrder(TreeNode root){
        if(root == null){
            return ;
        }
        preOrder(root.left);
        if(pre != null){
            diff = Math.min(root.val - pre.val, diff);
        }
        pre = root;
        preOrder(root.right);
    }
}
501. 二叉搜索树中的众数 - 力扣(LeetCode)

还是借助BST的性质,进行中序遍历,重点是统计maxCount和当前的nowCount,进行res数组的更新

class Solution {

    List<Integer> res = new ArrayList<>();

    int maxCount = 0;

    int nowCount = 0;

    TreeNode pre = null;

    public int[] findMode(TreeNode root) {
        inOrder(root);
        int[] resArray = new int[res.size()];
        for(int i = 0; i < res.size(); i++){
            resArray[i] = res.get(i);
        }
        return resArray;
    }

    public void inOrder(TreeNode root){
        if(root == null){
            return ;
        }
        inOrder(root.left);
        if(pre == null || pre.val != root.val){
            nowCount = 1;
        }else{
            nowCount++;
        }
        if(nowCount == maxCount){
            res.add(root.val);
        }
        if(nowCount > maxCount){
            res.clear();
            res.add(root.val);
            maxCount = nowCount;
        }
        pre = root;
        inOrder(root.right);
    }
}
小tips

Java中集合可以直接转成数组,用的是toArray()这个函数,但是转的是Object类型的数组

List<String> list=new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
// 使用无参的toArray()方法,默认的返回类型是Object []
Object[] objects = list.toArray();

所以真正做题时,只能遍历转数组

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

有点没懂

总体来说就是回溯找公共祖先,使用后序遍历(后序是天然的回溯过程)

  • 参数和返回值,返回值需要告诉我们是否找到了p和q,那么使用bool,但是题目要求返回公共节点,所以使用TreeNode,参数root,p,q

  • 终止条件,null,找到p和q

  • 单层递归逻辑,后序,左右中,重点在中,因为本体返回值是TreeNode,所以需要对其进行判断,判断就是需要实现的逻辑

    if(left != null && right != null){
        return root;
    }else if(left != null && right == null){
        return left;
    }else if(left == null && right != null){
        return right;
    }else{
        return 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;
        }else if(left != null && right == null){
            return left;
        }else if(left == null && right != null){
            return right;
        }else{
            return null;
        }
    }
}
posted @ 2025-06-11 16:43  泡芙猪  阅读(21)  评论(0)    收藏  举报