因为是二叉搜索树,所以可以用中序遍历来解决
# 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 findMode(self, root: Optional[TreeNode]) -> List[int]:
pre = None
cur = root
stack = []
res = []
count = 0
maxCount = 0
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
if not pre:
count = 1
else:
if cur.val == pre.val:
count += 1
else:
if count == maxCount:
res.append(pre.val)
elif count > maxCount:
res = [pre.val]
maxCount = count
count = 1
pre = cur
cur = cur.right
if count == maxCount:
res.append(pre.val)
elif count > maxCount:
res = [pre.val]
maxCount = count
return res