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

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

参考文章:代码随想录 

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

解题思路:通过二叉搜索树的特性来去解决,最小绝对差一定是发生在父子节点上的,因此可以通过中序遍历来比较父子节点的差值,利用双指针,一个指向子节点初值值pre=null,一个指向当前节点,若差值小于最小值则去更新最小值,然后将pre = node来去移动pre指针。最终将整个二叉树遍历结束后返回这个最小值。

int res = Integer.MAX_VALUE;
    TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {
        find(root);
        return res;
    }

    public void find(TreeNode node) {
        if (node == null) return;
        find(node.left);
        if (pre != null) {
            res = Math.min(res, node.val - pre.val);
        }
        pre = node;
        find(node.right);
    }

 501.二叉搜索树中的众数

参考文章:代码随想录 

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

解题思路:和上题思路基本一样,用中序遍历,两个指针,一个作为pre初始值为null,一个作为当前节点,通过比较是否相同来去计算出现次数,若大于等于maxCount,来去更新数组。需要注意的是若大于maxCount的时候需要将result数组清空再去添加当前节点的数值。

public class Leetcode501 {
    int maxCount = 0;
    int count = 0;
    List<Integer> list = new ArrayList<>();
    TreeNode pre = null;

    public int[] findMode(TreeNode root) {
        find(root);
        int[] arr = new int[list.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    public void find(TreeNode node) {
        if (node == null) return;
        find(node.left);
        if (pre == null) {
            count = 1;
        } else if (pre.val == node.val) {
            count++;
        } else {
            count = 1;
        }
        pre = node;
        if (count == maxCount) list.add(node.val);
        if (count > maxCount) {
            list.clear();
            list.add(node.val);
            maxCount = count;
        }
        find(node.right);
    }
}

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

参考文章:代码随想录 

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

解题思路:利用后序遍历,当遇到节点为q或是p的时候返回该节点,若是遇到节点为空时返回空,然后当前节点接受左右子树的返回结果,总共四种情况,需要了解到的是,当p或q本身刚好是公共祖先的情况下,其实这种情况在最开始的判断上已经包含到了,即遇到p或q就返回该节点,最终根节点就会返回p或q节点作为结果。

具体四种情况看代码:

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return root;
        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;
        if (left != null && right == null) return left;
        if (left == null && right != null) return right;
        if (left == null && right == null) return null;
        return root;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值