LC530.二叉搜索树的最小绝对差:
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
中序递归!
LC501.二叉搜索树中的众数
class Solution:
def __init__(self):
self.pre = TreeNode()
self.count = 0
self.max_count = 0
self.res = []
def findMode(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return None
self.searchBST(root)
return self.res
def searchBST(self, cur:TreeNode) -> None:
if not cur:
return None
self.searchBST(cur.left)
#处理第一个节点
if not self.pre:
self.count = 1
# 与前一个节点数值相同
elif self.pre.val == cur.val:
self.count += 1
# 与前一个节点数值不相同
else:
self.count = 1
self.pre = cur
if self.count == self.max_count:
self.res.append(cur.val)
if self.count > self.max_count:
self.max_count = self.count
self.res = [cur.val] # 清空self.result,确保result之前的的元素都失效
self.searchBST(cur.right)