Python easy understand solution


  • 1
    Y

    I use stack to store the node and traversal the tree. I use dictionary to count the frequency of occurrence of the value. After all, find the maximum and report.
    '''
    class Solution(object):

    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:return []
        stack=[root]
        dic={}
        while stack:
            node=stack.pop()
            dic[node.val]=dic.get(node.val,0)+1
            if not node.left and not node.right:continue
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        max_val=max(dic.values())
        result=[]
        for key in dic.keys():
            if dic[key]==max_val:
                result.append(key)
        return result

Log in to reply
 

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