前言
每日刷题,从己做起。
一、二叉搜索树最小绝对差?
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
global pre, minval
pre = None
minval = 10**5
self.traversal(root)
return minval
#
def traversal(self, root):
global pre, minval
if not root:
return None
self.traversal(root.left)
if pre and root.val - pre.val < minval:
minval = root.val - pre.val
pre = root
self.traversal(root.right)
二、二叉树的最近公共祖先
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:
return root
if left:
return left
return right
三、二叉搜索树的众数
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.searchercahshu(root)
return self.result
def searchercahshu(self, cur: Optional[TreeNode]):
if not cur:
return None
self.searchercahshu(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.maxcount:
self.result.append(cur.val)
if self.count > self.maxcount:
self.maxcount = self.count
self.result = [cur.val]
self.searchercahshu(cur.right)
总结
加油。