代码随想录算法训练营Day21|LC530 二叉搜索树的最小绝对差&LC501 二叉搜索树中的众数&LC236 二叉树的最近公共祖先

一句话总结:今天的题有点难度,(但不多)。

原题链接:530 二叉搜索树的最小绝对差

预先将ans设置为int型最大值,然后设置一个pre将要处理的节点的中序遍历序列的前一个节点,然后利用二叉搜索树的中序遍历的性质,不停更新ans值,返回这个ans即可。

class Solution {
    private TreeNode pre;
    private int ans = Integer.MAX_VALUE;

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return ans;
    }

    private void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        if (pre != null) ans = Math.min(ans, root.val - pre.val);
        pre = root;
        dfs(root.right);
    }
}

 另外需要指出的是二叉搜索树的与当前节点值差最小的值是其中序遍历序列的前一个节点而非一定是其左右子节点。

原题链接:二叉搜索树中的众数

最简单的做法是用哈希表保存中序遍历这个二叉搜索树的结果,然后对哈希表进行操作排序,取最大value的几个树即可。但对于二叉搜索树有着更简单的操作:利用三个数,pre保存之前处理的数字,cnt保存当前操作的数字出现的次数,以及mxCnt保存树中出现过的最大频次。然后利用二叉搜索树中值相同的几个数字一定出现在连续的中序遍历序列中,所以递归地使用中序遍历。

class Solution {
    List<Integer> ans = new LinkedList<>();
    int pre, cnt, mxCnt;
    public int[] findMode(TreeNode root) {
        dfs(root);
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); ++i) {
            res[i] = ans.get(i);
        }
        return res;
    }

    void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        update(root.val);
        dfs(root.right);
    }

    void update(int x) {
        if (x == pre) ++cnt;
        else {
            cnt = 1;
            pre = x;
        }
        if (cnt == mxCnt) ans.add(x);
        if (cnt > mxCnt) {
            mxCnt = cnt;
            ans.clear();
            ans.add(x);
        }
    }
}

原题链接:236 二叉树的最近公共祖先

此题参考Krahets解法

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == root || q == root) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) return right;
        if (right == null) return left;
        return root;
    }
}

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值