day 21 第六章 二叉树
今日内容
● 530.二叉搜索树的最小绝对差
● 501.二叉搜索树中的众数
● 236. 二叉树的最近公共祖先
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
# 501.二叉搜索树中的众数
pre = 10000000
maxNum = 0
res = []
def inorder(node, pre, num, maxNum, res):
if not node:
return num, pre, maxNum
num, pre, maxNum = inorder(node.left, pre, num, maxNum, res)
print(node.val, num, pre, maxNum, res)
if node.val==pre:
# print("xiangdeng",res)
num += 1
else:
if num > maxNum:
res.clear()
res.append(pre)
# print("qingchu", res)
maxNum = num
elif num == maxNum:
res.append(pre)
# print("jiashang", res)
num = 1
pre = node.val
num, pre, maxNum = inorder(node.right, pre, num, maxNum, res)
return num, pre, maxNum
num, pre, maxNum = inorder(root, 10000000, -1, 0, res)
if num > maxNum:
res.clear()
res.append(pre)
if num==maxNum:
res.append(pre)
return res
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 236. 二叉树的最近公共祖先
def searcher(node):
# 如果到了叶子,返回none
if not node:
return
# 如果找到了相同结点,返回结点
if node == p or node == q:
return node
# 递归寻找前结点,如果返回的都不是none,说明就是前结点
lef = searcher(node.left)
rig = searcher(node.right)
# 都为空说明都不在
if not lef and not rig:
return
# 如果两边都不为空
if lef and rig:
return node
# 左边为空,说明都在右边,反之同理
if not lef:
return rig
if not rig:
return lef
if not searcher(root):
return root
return searcher(root)