LeetCode寒假刷题 Day15


前言

今天是寒假LeetCode刷题打卡的第十五天,继续坚持、继续加油!也希望我的博文能够帮助到大家,若有疑问,可以随时私信Call我!

一、231. 2的幂

1. 题目描述

231. 2的幂

2. 代码实现

class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 0) return false;
        long x = (long) n;
        return (x & (-x)) == x;
    }
}

注:利用快速排序的性质,当找到第K大的元素后便返回。

二、235. 二叉搜索树的最近公共祖先

1. 题目描述

235. 二叉搜索树的最近公共祖先

2. 代码实现

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        ArrayList <Integer> list=new ArrayList<Integer>();
        int count=0;
        int val=0;
        //System.out.println("isSun:"+isSun(p,q));
        //System.out.println(val=);
        dfs(root,list,p,q,val);
        val=list.get(0);
        return new TreeNode(val);
    }
    void dfs(TreeNode root,ArrayList<Integer> list,TreeNode p, TreeNode q,int val)
    {
        if(list.size()>=1)
            return;
        if(root!=null)
        {
            dfs(root.left,list,p,q,val);
            dfs(root.right,list,p,q,val);
            if(isSun(root,p)&&isSun(root,q))
                val=root.val;
            //System.out.println("isSun:"+val);
            if(val!=0)
                list.add(val);
        }
    }
    boolean isSun(TreeNode p,TreeNode q)
    {
        if(p!=null)
        {
            if(p==q)
                return true;
            return isSun(p.left,q)||isSun(p.right,q);
        }
        return false;
    }
}

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

1. 题目描述

难度:中等
236. 二叉树的最近公共祖先

2. 代码实现

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        ArrayList <Integer> list=new ArrayList<Integer>();
        int count=0;
        int val=Integer.MAX_VALUE;
        //System.out.println("isSun:"+isSun(p,q));
        //System.out.println(val=);
        dfs(root,list,p,q,val);
        val=list.get(0);
        return new TreeNode(val);
    }
    void dfs(TreeNode root,ArrayList<Integer> list,TreeNode p, TreeNode q,int val)
    {
        if(list.size()>=1)
            return;
        if(root!=null)
        {
            dfs(root.left,list,p,q,val);
            dfs(root.right,list,p,q,val);
            if(isSun(root,p)&&isSun(root,q))
                val=root.val;
            if(val!=Integer.MAX_VALUE)
                list.add(val);
        }
    }
    boolean isSun(TreeNode p,TreeNode q)
    {
        if(p!=null)
        {
            if(p==q)
                return true;
            return isSun(p.left,q)||isSun(p.right,q);
        }
        return false;
    }
}

总结

以上就是今天 LeetCode寒假刷题 Day15 做的三道题。若有任何疑问,欢迎私信或评论区留言鸭!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值