530.二叉搜索树的最小绝对差
# 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 __init__(self):
self.vec=[]
def traversal(self,root):
if not root:
return
self.traversal(root.left)
self.vec.append(root.val)
self.traversal(root.right)
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
self.vec=[]
self.traversal(root)
result=float(inf)
for i in range(1,len(self.vec)):
if len(self.vec)<=1:
return 0
result=min(result,self.vec[i]-self.vec[i-1])
return result
501.二叉搜索树中的众数
defaultdict
:在普通字典中,当你尝试访问一个不存在的键时,Python 会抛出 KeyError
异常。而 defaultdict
允许你在创建字典时指定一个默认值的工厂函数,当访问一个不存在的键时,它会自动创建该键,并使用默认值工厂函数返回的值作为该键的值,避免了 KeyError
异常的发生。
# 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 findM(self,root,defaultmap):
if not root:
return
defaultmap[root.val]+=1
self.findM(root.left,defaultmap)
self.findM(root.right,defaultmap)
def findMode(self, root: Optional[TreeNode]) -> List[int]:
from collections import defaultdict
defaultmap=defaultdict(int)
self.findM(root,defaultmap)
result=[]
if not root:
return result
maxd=max(defaultmap.values())
#找字典中最大的值的方法
for key,value in defaultmap.items():
if value==maxd:
result.append(key)
return result
236. 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
# 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 root is p or root is q or root is None:
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
else:
return right