231 2的幂
class Solution :
def isPowerOfTwo ( self, n: int ) - > bool :
if n == 0 :
return False
while n% 2 == 0 :
n /= 2
return n== 1
class Solution :
def isPowerOfTwo ( self, n: int ) - > bool :
if n == 0 :
return False
return n & ( - n) == n
class Solution :
def isPowerOfTwo ( self, n: int ) - > bool :
return n> 0 and n& ( n- 1 ) == 0
235 二叉搜索树的最近公共祖先
class Solution :
def lowestCommonAncestor ( self, root: 'TreeNode' , p: 'TreeNode' , q: 'TreeNode' ) - > 'TreeNode' :
while ( root. val - p. val) * ( root. val - q. val ) > 0 :
if root. val - p. val > 0 :
root = root. left
else :
root = root. right
return root
class Solution :
def lowestCommonAncestor ( self, root: 'TreeNode' , p: 'TreeNode' , q: 'TreeNode' ) - > 'TreeNode' :
if not root : return None
p_path = self. getPath( root, p)
q_path = self. getPath( root, q)
p_len = len ( p_path)
q_len = len ( q_path)
min_len = min ( p_len, q_len)
for i in range ( min_len) :
if p_path[ i] == q_path[ i] :
max_index = i
continue
return p_path[ max_index]
def getPath ( self, root, node) :
node_path = [ root]
while root != node:
if root. val < node. val:
root = root. right
node_path. append( root)
if root. val > node. val:
root = root. left
node_path. append( root)
return node_path
236 二叉树的最近公共祖先
class Solution :
def lowestCommonAncestor ( self, root: 'TreeNode' , p: 'TreeNode' , q: 'TreeNode' ) - > 'TreeNode' :
if ( not root) or ( root == q) or ( root == p) :
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
if left and right: return root