一、530.二叉搜索树的最小绝对差
题目
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
![icon-default.png?t=N2N8](https://i-blog.csdnimg.cn/blog_migrate/dae51f0b6b58667fea1775fa072b8fd7.png)
from collections import deque
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
res = []
r = float('inf') # 正无穷
def builtlist(root):
if not root:
return None
if root.left:
builtlist(root.left)
res.append(root.val)
if root.right:
builtlist(root.right)
builtlist(root)
for i in range(len(res)-1):
r = min((res[i+1]-res[i]),r) # 这里的等于必须是r ,这样r 才能被替换,一直保留较小的值
return r
1.因为是二叉搜素数,用中序遍历递归,存一个有序数组
2.遍历数组,让相邻数值相减,取最小值,r要参与循环
# 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]:
res =[]
r = []
dic = {}
def builtlist(root): # 中序递归 得到列表
if not root:
return None
if root.left:
builtlist(root.left)
res.append(root.val)
if root.right:
builtlist(root.right)
builtlist(root)
for i in res: # 对列表出现的数字的频次进行统计
if i in dic:
dic[i]+=1
else:
dic[i] = 1
cur = sorted(dic.items(),key = lambda x:x[1],reverse = True) # 按照频次进行排序
r.append(cur[0][0]) # 第一个肯定是众数
for i in range(len(cur)-1): # 对有可能是多个众数的进行判断
if cur[0][1]==cur[i+1][1]: # 只有等于第一个频次的元组才是需要的
r.append(cur[i+1][0])
return r
1.先用中序遍历得到一个数值列表
2.利用字典统计每个数字出现的频率,并根据频次降序排序
3第一个元素一定是众数,但需要判断有多个众数的情况。判断条件为 用第一个频次和后续的频次比较。相等则追加到输出列表中。
三、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 not root or root == p or root == q: # 终止条件 找到了p或者q或者节点为空
return root # 返回节点
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# 左右节点只有两种状态,非空 和 空
# 不为空 说明找到目标值了 排列组合 一共四种情况
if left and right: # 左不空,右不空 说明root就是最近公共祖先
return root
if left and not right: # 左不空,右空 # 左节点不为空,说明在左节点这边找了一个目标值
return left
if right and not left: # 左空,右不空
return right
else : # 左空,右空
return None