程式設計實踐筆記No.15
阿新 • • 發佈:2021-01-28
技術標籤:程式設計實踐
程式設計實踐筆記No.15
寫在最前面,程式設計一直是我的短板,希望在leetcode練習中獲得進步!
參考Datawhale組隊學習中“LeetCodeTencent”
題目一215 陣列中的第K個最大元素
給定一個整數,編寫一個函式來判斷它是否是 2 的冪次方。
程式碼
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for i in range(32):
mask = 1 << i
if n ^ mask == 0:
return True
return False
題目二235 二叉搜尋樹的最近公共祖先
給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉搜尋樹: root = [6,2,8,0,4,7,9,null,null,3,5]
程式碼
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
def getPath(root: TreeNode, target: TreeNode) -> List[TreeNode]:
path = list()
node = root
while node != target:
path.append( node)
if target.val < node.val:
node = node.left
else:
node = node.right
path.append(node)
return path
path_p = getPath(root, p)
path_q = getPath(root, q)
ancestor = None
for u, v in zip(path_p, path_q):
if u == v:
ancestor = u
else:
break
return ancestor
題目三 236 二叉樹的最近公共祖先
給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]。
程式碼
# 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':
if not root or root == p or root == q: return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if not left and not right: return # 1.
if not left: return right # 3.
if not right: return left # 4.
return root # 2. if left and right: