第一题
中序遍历,单调递增,可以排序
双指针法,使用min不断更新最新最小值
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def __init__(self):
self.pre=None
self.res=float('inf')
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return
self.getMinimumDifference(root.left)
if self.pre!=None:
self.res=min(self.res,root.val-self.pre.val)
self.pre=root
self.getMinimumDifference(root.right)
return self.res
第二题
中序遍历
双指针法,在遍历到中间元素时,对先对count进行处理。随后,当count==maxcount,元素加入数组;若count>maxcout,更新maxcount,清空数组,加入元素
class Solution(object):
def __init__(self):
self.pre=None
self.maxcount=0
self.count=0
self.res=[]
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return
self.findMode(root.left)
if self.pre is None:
self.count=1
elif root.val==self.pre.val:
self.count+=1
else:
self.count=1
self.pre=root
if self.count==self.maxcount:
self.res.append(root.val)
if self.count>self.maxcount:
self.maxcount=self.count
self.res=[root.val]
self.findMode(root.right)
return self.res
第三题:
后序遍历
在后续时,根据不同情况分为三类,返回root,left,right
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None:
return None
if root is p or root is q:
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left!=None and right!=None:return root
if left!=None and right==None:return left
if left==None and right!=None:return right