leetcode 530 二叉树的最小绝对差
目前对于代码掌握程度还太低,所以对于一个题目的思路先从会用的方法想思路,比如暴力解法
对于二叉树的最小绝对差,因为是二叉搜索树,所以用中序遍历转为有序数组,然后求取差值
class Solution:
def __init__(self):
self.vec = []
def traversal(self, root):
if not root:
return
self.traversal(root.left)
self.vec.append(root.val)
self.traversal(root.right)
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.traversal(root)
if len(self.vec) < 2:
return 0
result = float('inf')
for i in range(1, len(self.vec)):
result = min(result, self.vec[i] - self.vec[i - 1])
return resul
leetcode 501 二叉搜索树中的众数
迭代&字典:
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
freq = defaultdict(int)
result = []
if not root:
return result
self.searchBST(root, freq)
max_freq = max(freq.values())
for key, value in freq.items():
if value == max_freq:
result.append(key)
return result
def searchBST(self, cur, freq):
if not cur:
return
freq[cur.val] += 1
self.searchBST(cur.left, freq)
self.searchBST(cur.right, freq)
leetcode 236 二叉树的最近公共祖先
递归加回溯有点难
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root == q or root == p or root is None:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is not None and right is not None:
return root
elif left is not None and right is None:
return left
elif right is not None and left is None:
return right
else:
return None