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

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

思路:

1. 利用双指针,在遍历的同时更新最小绝对差,并返回;

2. 参数:节点;返回值:无;

3. 终止条件:遇到空节点;

4. 单层递归逻辑:中序遍历;中节点操作:更新最小绝对差,pre = node。

class Solution {
    TreeNode pre;
    int result = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        if(root == null) return 0;
        traversal(root);
        return result;
    }
    public void traversal(TreeNode node){
        if(node == null) return;
        traversal(node.left);
        if(pre!=null) result = Math.min(result,node.val-pre.val);
        pre = node;
        traversal(node.right);
    }
}

501.二叉搜索树中的众数

思路:

1. 初始化count=1;中序遍历,比较前后两个节点的值,若一致,count++;若不一致,count=1;找出最大频率maxCount;

2. 如果频率 count 等于 maxCount,把元素加入结果集res[];若count 大于 maxCount,更新maxCount,并清空结果集res。

class Solution {
    ArrayList<Integer> res;
    int maxCount;
    int count;
    TreeNode pre;
    public int[] findMode(TreeNode root) {
        res = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        find(root);
        int[] result = new int[res.size()];
        for(int i = 0; i<res.size();i++){
            result[i] = res.get(i);
        }
        return result;
    }
    public void find(TreeNode node){
        if(node == null) return;
        find(node.left);
        int nodeValue = node.val;
        if(pre == null || nodeValue != pre.val){
            count = 1;
        } else {
            count++;
        }
        if(count>maxCount){
            res.clear();
            res.add(nodeValue);
            maxCount = count;
        } else if (count == maxCount){
            res.add(nodeValue);
        }
        pre = node;
        find(node.right);
    }
}

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

力扣

思路:

1. 参数:根节点,2个指定节点;返回值:最近公共节点;

2. 终止条件:遇到空节点;

3. 后序遍历(因为需要回溯),根据左右子树的返回值,来处理中节点。如果递归遍历遇到q,就返回q;遇到p 就返回p。若左右子树的返回值都不为空,那么此时的中节点,就是q 和p 的最近祖先。

class Solution {
    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 null;
        if(left == null && right != null) return right;
        if(left != null && right == null) return left;
        return root;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值