day21||第六章 二叉树part07● 530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

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

先按照直白方式写:将二叉搜索树中序遍历转换为有序数组,然后求最小的相邻元素的差值。

class Solution {
    private List<Integer> list = new ArrayList<>();
    public int getMinimumDifference(TreeNode root) {
        traversal(root);
        int min =Integer.MAX_VALUE;
        for(int i = 1;i<list.size();i++){
            min = Math.min(min,list.get(i)-list.get(i-1));
        }
        return min;
    }
    private void traversal(TreeNode root){
        if(root == null){
            return;
        }
        traversal(root.left);
        list.add(root.val);
        traversal(root.right);
    }

}

双指针法

对于递归来说,哪个遍历,中序遍历举例,那么递归函数出现在左和右,具体操作出现在中

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

 ● 501.二叉搜索树中的众数 

双指针写法

学到如何将List<Integer>转化为int[]的方法,利用stream流。

ArrayList 转换成 int[ ] 数组..._arraylist转int[]-CSDN博客

count计数计的是cur所指向数字的频次

class Solution {
    private TreeNode pre = null;
    private int count = 0;
    private int maxcount = 0;
    List<Integer> res = new ArrayList<>();
    public int[] findMode(TreeNode root) {
        traversal(root);
        return res.stream().mapToInt(Integer::valueOf).toArray();//将List<Integer> 转化为int[];
    }
    private void traversal(TreeNode cur){
        if(cur == null) return;
        traversal(cur.left);

        if(pre==null) count=1;
        else if(pre.val == cur.val) count++;//这一部分处理count计数
        else count=1;

        pre=cur;

        if(count==maxcount) res.add(cur.val);
        if(count>maxcount){
            maxcount = count;//这一部分处理res,放答案
            res.clear();
            res.add(cur.val);
        }
        traversal(cur.right);
        return;
    }
}

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值