前段时间一直在忙参加学术会议做oral presentation的事情,把算法题落下了,现在来女娲补天了。
一、leetcode刷题
1.leetcode题目 530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
解决:
①迭代法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
stack = []
cur = root
if not root:
return 0
pre = None
ans =10**9
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if pre:
ans = min(ans,cur.val-pre.val)
pre = cur
cur = cur.right
return ans
②递归法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
pre = 10**9
ans = 10**9
def dfs(root):
nonlocal pre,ans
if root == None:
return
dfs(root.left)
ans = min(ans,abs(root.val-pre))
pre = root.val
dfs(root.right)
dfs(root)
return ans
2.leetcode题目 501. 二叉搜索树中的众数 - 力扣(LeetCode)
解决:
dfs
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
ans = collections.defaultdict(int)
def dfs(root,ans):
if root is None:
return
dfs(root.left,ans)
ans[root.val] += 1
dfs(root.right,ans)
if root is None:
return []
dfs(root,ans)
result = []
maxx = max(ans.values())
for key,value in ans.items():
if value == maxx:
result.append(key)
return result
3.leetcode题目 236. 二叉树的最近公共祖先 - 力扣(LeetCode)
思路:后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中节点的逻辑。
解决:
# 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 root is None or root==p or root==q:
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
if left is None:
return right
return left