530.二叉搜索树的最小绝对差
思路:
非常简单,因为是二叉搜索树,所以只需要中序遍历,即可将其升序排列,使用列表将其存储也行,使用指针直接相减也行
代码:
列表法
# 二叉树节点的定义
# 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:
result = []
# 定义深度优先搜索函数
def dfs(node):
if node == None:
return
dfs(node.left)
result.append(node.val)
dfs(node.right)
# 调用深度优先搜索函数遍历二叉树
dfs(root)
# 如果二叉树节点数量小于2,返回0
if len(result) < 2:
return 0
# 初始化最小差值为正无穷
res = float('inf')
# 遍历结果数组,计算相邻节点的差值,更新最小差值
for i in range(1, len(result)):
cur = abs(result[i] - result[i - 1])
res = min(cur, res)
# 返回最小差值
return res
501.二叉搜索树中的众数
思路:
既然是二叉搜索树,中序遍历就是有序的,使用cur和pre(node)指针,即可,若pre和cur相等,count就加1,若不等就再令count为0,并且每次重新判断count与maxcount的关系,count较大时更新maxcount与result,count与maxcount相等时,将此时的cur(node)加入result中,最后返回result即可。
代码:
# 二叉树节点的定义
# 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]:
count = 0 # 记录当前节点值的出现次数
maxcount = 0 # 记录出现次数最多的节点值的出现次数
pre = None # 用于记录前一个访问的节点
result = [] # 存储出现次数最多的节点值
def dfs(node):
nonlocal count, maxcount, pre, result
if node == None:
return
dfs(node.left)
# 检查当前节点值与前一个节点值的关系,更新计数器
if pre != None:
if pre.val == node.val:
count += 1
else:
count = 1
else:
count = 1
pre = node # 更新前一个节点为当前节点
# 根据当前节点值的出现次数更新最大出现次数和结果列表
if count == maxcount:
result.append(node.val)
elif count > maxcount:
maxcount = count
result = [node.val]
dfs(node.right)
dfs(root)
return result
236. 二叉树的最近公共祖先
代码:
# 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 == 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
if left is None and right is not None:
return right
elif left is not None and right is None:
return left
else:
return None