文章目录
前言
今天是寒假LeetCode刷题打卡的第十五天,继续坚持、继续加油!也希望我的博文能够帮助到大家,若有疑问,可以随时私信Call我!
一、231. 2的幂
1. 题目描述
2. 代码实现
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 0) return false;
long x = (long) n;
return (x & (-x)) == x;
}
}
注:利用快速排序的性质,当找到第K大的元素后便返回。
二、235. 二叉搜索树的最近公共祖先
1. 题目描述
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 做的三道题。若有任何疑问,欢迎私信或评论区留言鸭!