python simple and clear solution - O(n) time, O(1) space


  • 0
    A

    class Solution(object):

    def __init__(self):
        self.max_freq = -100
        self.count = -200
        self.cur_val = None
        self.res = []
        
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root==None:
            return self.res
        
        self.inOrderTraversal(root)
        self.update_res()
        return self.res
        
    def inOrderTraversal(self, root):
        if root == None:
            return
        self.inOrderTraversal(root.left)
        
        if root.val != self.cur_val:
            self.update_res()
            self.count=1
            self.cur_val = root.val
        else:
            self.count+=1
        
        self.inOrderTraversal(root.right)
    
    def update_res(self):
        if self.count == self.max_freq:
            self.res.append(self.cur_val)
        elif self.count > self.max_freq:
            self.max_freq = self.count
            self.res = []
            self.res.append(self.cur_val)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.