530 二叉搜索树的最小绝对差
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.last=float('inf')
self.temp=float('inf')
def sub(root):
if not root:
return
sub(root.left)
if abs(root.val-self.last)<self.temp:
self.temp=abs(root.val-self.last)
self.last=root.val
sub(root.right)
sub(root)
return self.temp
501 二叉搜索树中的众数
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
self.rets=[]
self.times=0
self.lasttime=0
self.last=None
def sub(root):
if not root:
return
sub(root.left)
if root.val==self.last:
self.lasttime+=1
else:
self.last=root.val
self.lasttime=1
if self.times<self.lasttime:
self.rets=[self.last]
self.times=self.lasttime
elif self.times==self.lasttime:
self.rets.append(self.last)
sub(root.right)
sub(root)
return self.rets
236 二叉树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ret=None
def sub(root,left,right):
if not root:
return False
l=sub(root.left,left,right)
r=sub(root.right,left,right)
if (l and r)or((root.val==p.val or root.val==q.val) and (l or r)):
self.ret=root
if l or r or root.val==p.val or root.val==q.val:
return True
return False
sub(root,p,q)
return self.ret