501. Find Mode in Binary Search Tree
中序遍历,得到单调递增的数组,然后记录最大次数,等于最大次数:append,大于最大次数:清空+append
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
node = root
res = []
maxNum = curNum = 0
pre = None
while stack or node:
while node:
stack.append(node)
node = node.left
if stack:
node = stack.pop()
if node.val != pre:
curNum = 0
curNum += 1
if curNum == maxNum:
if not res or node.val != res[-1]:
res.append(node.val)
elif curNum > maxNum:
maxNum = curNum
res = [node.val]
pre = node.val
node = node.right
return res