Bootstrap

Python | Leetcode Python题解之第501题二叉搜索树中的众数

题目:

题解:

# 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: TreeNode) -> List[int]:
        # 迭代
        st = collections.deque()
        cur = root
        pre = None
        maxCount, count = 0, 0
        result = list()
        while cur or st:
            if cur:             # 指针访问节点,一直访问到最底层
                st.append(cur)  # 将节点放入栈内
                cur = cur.left  # 左节点
            else:
                cur = st.pop()  # 中节点
                if pre == None: # 第一个节点
                    count = 1
                elif pre.val == cur.val: # 与前一个节点数值相同
                    count += 1
                else:
                    count = 1
                if count == maxCount:
                    result.append(cur.val)
                if count > maxCount:
                    maxCount = count
                    result = list()
                    result.append(cur.val)
                pre = cur
                cur = cur.right
        return result
        # 递归
        '''
        self.count = 0
        self.maxCount = 0
        self.pre = None
        self.result = list()
        def searchBST(cur: TreeNode):
            if cur == None:
                return
            searchBST(cur.left)
            if self.pre == None:
                self.count = 1
            elif self.pre.val == cur.val:
                self.count += 1
            else:
                self.count = 1
            self.pre = cur

            if self.count == self.maxCount:
                self.result.append(cur.val)
            if self.count > self.maxCount:
                self.maxCount = self.count
                self.result = list()
                self.result.append(cur.val)
            
            searchBST(cur.right)
            return
        
        searchBST(root)
        return self.result
        '''
;