代码随想录算法训练营第二十天 | leetcode 530. 二叉搜索树的最小绝对差,501. 二叉搜索树中的众数,236. 二叉树的最近公共祖先
530. 二叉搜索树的最小绝对差
题目:
题目链接:530. 二叉搜索树的最小绝对差
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
res = []
r = float("INF")
def buildaList(root): #中序遍历,转换为有序数组
if not root:
return None
if root.left:
buildaList(root.left)
res.append(root.val)
if root.right:
buildaList(root.right)
return res
buildaList(root)
for i in range(len(res) - 1): #统计有序数组间的绝对值差值
r = min(abs(res[i] - res[i+1]), r)
return r
501. 二叉搜索树中的众数
题目:给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
题目链接:501. 二叉搜索树中的众数
class Solution:
def __init__(self):
self.pre = TreeNode()
self.count = 0
self.maxcount = 0
self.result = []
def findMode(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return None
self.search_BST(root)
return self.result
def search_BST(self, cur: TreeNode) -> None:
if not cur:
return None
self.search_BST(cur.left)
if not self.pre: # 从第一个结点开始
self.count = 1
elif self.pre.val == cur.val: # 若相邻结点相同则计数加1
self.count += 1
else:
self.count = 1
self.pre = cur # 更新上一个结点
if self.count == self.maxcount:
self.result.append(cur.val)
if self.count > self.maxcount:
self.maxcount = self.count
self.result = [cur.val] # 清空之前所存的元素
self.search_BST(cur.right)
236. 二叉树的最近公共祖先
题目:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
题目链接:236. 二叉树的最近公共祖先
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 left and right: # 如果left 和 right都不为空,说明此时root就是最近公共节点。
return root
if left: # 如果有左子树而无右子树,就处理左子树的返回值
return left
return right # 反之亦然