LeetCode刷题day21|530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236二叉树的最近公共祖先

文章目录

  • 一、530.二叉搜索树的最小绝对差
  • 二、501二叉搜索树中的众数
  • 三、236二叉树的最近公共祖先

一、530.二叉搜索树的最小绝对差

有两个容易踩坑的地方:

  1. 对于全局变量一定要初始化!
	TreeNode pre = null;
    int res = Integer.MAX_VALUE;
  1. 在取最小值前一定要记得判断pre是否为空
	if(pre!=null)
            res = Math.min(res, cur.val-pre.val);  

以下是代码部分:

	// 重要的点:
    //踩坑的地方:两个值都要初始化
    TreeNode pre = null;
    int res = Integer.MAX_VALUE;
    //代码随想录中的方法
    public int getMinimumDifference2(TreeNode root) {
        inorder(root);
        return res;
    }

    private void inorder(TreeNode cur){
        if(cur == null)
            return;

        inorder(cur.left);
        //这里记得判断pre是否为空
        if(pre!=null)
            res = Math.min(res, cur.val-pre.val);
        pre= cur;
        inorder(cur.right);
    }        

二、501二叉搜索树中的众数

有两个需要注意的点:

  1. 一定要记得更新pre的值
  2. 对于list,可以直接调用clear()方法清空元素。

另外,看卡哥视频学习的知识点:
3. 涉及到二叉搜索树的题目,一般都是中序遍历
4. 如果要遍历全部二叉树,则递归函数的类型一般为void,处理的数据存放到全局变量中; 如果是遍历局部二叉树,则递归函数的类型一般是TreeNode

以下是代码部分:

//代码随想录中的方法
    public int[] findMode2(TreeNode root) {

        inorder2(root);
        int[] res = new int[list.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }

        return res;
    }

    private void inorder2(TreeNode cur){

        if(cur == null)
            return;

        inorder2(cur.left);
        if(pre == null)
            count =1;
        else if(pre.val == cur.val)
            count++;
        else
            count = 1;
        //踩坑的地方:忘记更改pre的值
        pre = cur;

        //结果收集
        if(count == maxCount)
            list.add(cur.val);
        if(count > maxCount){
            maxCount = count;
            list.clear();
            list.add(cur.val);
        }

        inorder2(cur.right);
    }

三、236二叉树的最近公共祖先

这道题不会,直接看的视频讲解。
以下是代码部分:

// 代码随想录的方法
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {

        //遇到根节点
        if(root == null)
            return null;

        //遇到目标值节点,返回目标值节点
        if(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;
    }

你可能感兴趣的:(leetcode,算法,java)