How about using Python generator?


  • 0
    H

    First, use a generator to do bfs, which will output all values sorted.
    Second, find the modes.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def bfs(self, root):
            if root:
                for n in self.bfs(root.left):
                    yield n
                yield root.val
                for n in self.bfs(root.right):
                    yield n
                
        def findMode(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            ns = self.bfs(root)
            cur = None
            count = 0
            mc = 1
            ans = []
            for n in ns:
                if n == cur:
                    count += 1
                else:
                    if count > mc:
                        mc = count
                        ans = [cur]
                    elif count == mc:
                        ans.append(cur)
                    cur = n
                    count = 1
            if count > mc:
                return [cur]
            elif count == mc:
                ans.append(cur)
            return ans
            
    

Log in to reply
 

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