代码随想录day21

Day21

今日任务

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

代码实现

    int min = Integer.MAX_VALUE;

    TreeNode pre = null;

    //由于要比较的相邻的两个节点之间的值,所以采用中序遍历
    public int getMinimumDifference(TreeNode root) {
        getMin(root);
        return min;
    }

    public void getMin(TreeNode cur) {
        if (cur == null) return;
        getMin(cur.left);
        if (pre != null) {
            min = Math.min(min, Math.abs(pre.val - cur.val));
        }
        pre = cur;
        getMin(cur.right);
    }
public List<Integer> result;
    public int count;

    public int maxCount;


    public int[] findMode(TreeNode root) {
        if (root == null) return null;
        result = new ArrayList<>();
        count = 0;
        maxCount = 0;
        traversal(root);

        return result.stream().mapToInt(i -> i).toArray();

    }

    public void traversal(TreeNode cur) {
        if (cur == null) return;
        traversal(cur.left);
        if (pre != null) {
            if (pre.val != cur.val) {
                count = 1;
            } else {
                count++;
            }
        } else {
            count = 1;
        }
        if (count > maxCount) {
            result.clear();
            maxCount = count;
            result.add(cur.val);

        } else if (count == maxCount) {
            result.add(cur.val);
        }
        pre = cur;
        traversal(cur.right);
    }
    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;
        if (left != null) return left;
        if (right != null) return right;
        return null;
    }

今日总结

  1. 对二叉树的递归还没有真正理解,或者说对于递归还没有真正理解,通过递归,可以做到在遍历二叉树的时候先处理下边的元素,再处理上边的元素,这很重要,同时也是前序中序后序三种遍历不同的点;
  2. 状态不好,太困了,第一道题想了一下没写出来,又陷入昨天的循环,还是没有完全理解二叉搜索树中的双指针,第二题小技巧很难想到,第三题更不用说,看完也不知道怎么能想到;
  3. 股票今天小红1.76,假如每天能红1个点,这个月就回本了
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值