代码随想录算法训练营第十八天|530.二叉搜索树的最小绝对差 , 501.二叉搜索树中的众数 ,236. 二叉树的最近公共祖先

二叉搜索树中序遍历得到的值序列是递增有序的
利用好这个特性!

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

题目链接/文章讲解:代码随想录

视频讲解:二叉搜索树中,需要掌握如何双指针遍历!| LeetCode:530.二叉搜索树的最小绝对差_哔哩哔哩_bilibili

class Solution {
    TreeNode pre;
    int result = Integer.MAX_VALUE;

    public int getMinimumDifference(TreeNode root) {
        if (root == null) {
            return 0;
        }
        helper(root);
        return result;
    }

    public void helper(TreeNode root) {
        if (root == null) {
            return;
        }
        helper(root.left);
        if (pre != null) {
            result = Math.min(result, root.val - pre.val);
        }
        pre = root;
        helper(root.right);
    }
}

 501.二叉搜索树中的众数 

代码随想录

视频讲解:不仅双指针,还有代码技巧可以惊艳到你! | LeetCode:501.二叉搜索树中的众数_哔哩哔哩_bilibili

class Solution {
    ArrayList<Integer> list;
    TreeNode pre;
    int count;
    int maxCount;

    public int[] findMode(TreeNode root) {
        list = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        helper(root);
        int ans[] = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }

    public void helper(TreeNode root) {
        if (root == null) {
            return;
        }
        helper(root.left);
        if (pre == null || pre.val != root.val) {
            count = 1;
        } else {
            count++;
        }
        if (count > maxCount) {
            list.clear();
            list.add(root.val);
            maxCount = count;
        } else if (count == maxCount) {
            list.add(root.val);
        }
        pre = root;

        helper(root.right);
    }
}

 236. 二叉树的最近公共祖先 

代码随想录

视频讲解:自底向上查找,有点难度! | LeetCode:236. 二叉树的最近公共祖先_哔哩哔哩_bilibili

想要从下往上处理一定是后序遍历,如果在递归中找到了p或者q就不需要继续寻找了,因为此时就是最近公共祖先。


class Solution {
    public TreeNode lowestCommonAncestor(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) { 
            // 若未找到节点 p 或 q
            return null;
        } else if (left == null && right != null) { 
            // 若找到一个节点
            return right;
        } else if (left != null && right == null) {
             // 若找到一个节点
            return left;
        } else { // 若找到两个节点
            return root;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值