231.2的幂
解法一:最朴素的方法,依次除二判断。如果一个数是2的幂,那么不断除2肯定会得到1。反正亦然,如果不能通过反复除二得到1,那么一定不是2的幂。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
while n :
if n < 1: # 剪枝
return False
if n == 1:
return True
else:
n /= 2
return False
解法二:位运算
如果一个数是2的幂,那么其二进制有且仅有一位为1。因此使用与运算可轻易得到结果。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
return n & (n - 1) == 0
235.二叉搜索树的最近公共祖先
此题的关键就是意识到,自顶向下遍历时,第一个val在要求的两个结点之间的结点就是最近公共祖先。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
p, q = p.val, q.val
if p > q:
p, q = q, p
node = root
while node:
if p <= node.val <= q:
return node
elif node.val < p: # 根节点小于最小值,则肯定在右子树中
node = node.right
else: # 否则在左子树中
node = node.left
时间复杂度O(n)
,空间复杂度O(1)
。
236.二叉树的最近公共祖先
虽然只比235少了一个条件,但是难度上升了好几个档次。
具体思路参考高star解析:后续遍历dfs
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q:
# 如果root为空或者为p、q,向上返回root
return root
left = self.lowestCommonAncestor(root.left, p, q)# 向左子树递归
right = self.lowestCommonAncestor(root.right, p, q)# 向右子树递归
if not left and not right: return None # 左右都空的时候,向上返回空
if not left: return right # 左子树为空的时候,返回右子树
if not right: return left # 右子树为空的时候,返回左子树
return root # 都非空的时候,返回root