501. 二叉搜索树中的众数

501. 二叉搜索树中的众数

python 复制代码
# 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]:
        self.mode = []
        self.curCount = 0
        self.maxCount = 0
        self.prev = None
        self.traverse(root)
        return self.mode 
    
    def traverse(self, root):
        if not root:
            return

        self.traverse(root.left)

        if not self.prev:
            self.curCount = 1
            self.maxCount = 1
            self.mode.append(root.val)
        else:

            if root.val == self.prev.val:
                self.curCount += 1
                # root.val 是众数
                if self.curCount == self.maxCount:
                    self.mode.append(root.val)
                elif self.curCount > self.maxCount:
                    # 更新众数
                    self.mode.clear()
                    self.maxCount = self.curCount
                    self.mode.append(root.val)

            if root.val != self.prev.val:
                # root.val 不重复的情况
                self.curCount = 1
                if self.curCount == self.maxCount:
                    self.mode.append(root.val)

        # 更新prev 
        self.prev = root
        self.traverse(root.right)
相关推荐
EXtreme353 天前
【数据结构】彻底搞懂二叉树:四种遍历逻辑、经典OJ题与递归性能全解析
c语言·数据结构·算法·二叉树·递归
漫随流水3 天前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
漫随流水3 天前
leetcode算法(429.N叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水3 天前
leetcode算法(116.填充每个节点的下一个右侧节点指针)
数据结构·算法·leetcode·二叉树
R-G-B3 天前
BM28 二叉树的最大深度
数据结构·算法·二叉树·bm28·二叉树的最大深度
漫随流水4 天前
leetcode算法(111.二叉树的最小深度)
数据结构·算法·leetcode·二叉树
星火开发设计4 天前
二叉树详解及C++实现
java·数据结构·c++·学习·二叉树·知识·期末考试
漫随流水4 天前
leetcode算法(637.二叉树的层平均值)
数据结构·算法·leetcode·二叉树
漫随流水4 天前
leetcode算法(102.二叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水4 天前
leetcode算法(二叉树的层序遍历Ⅱ)
数据结构·算法·leetcode·二叉树