Skip to content

Latest commit

 

History

History
121 lines (95 loc) · 2.74 KB

501.md

File metadata and controls

121 lines (95 loc) · 2.74 KB
  1. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
   1
    \
     2
    /
   2
return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

my thoughts:

1. traversal the tree and frequency count
output most frequent elements


my solution:

# 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 findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        self.f = {}
        
        def tra(n):
            if not n:
                return
            if n.val in self.f:
                self.f[n.val] = self.f[n.val] + 1
            else:
                self.f[n.val] = 1
            tra(n.left)
            tra(n.right)
            
        tra(root)
        max = 0
        res = []
        for e in self.f:
            if self.f[e] > max:
                max = self.f[e]
        for e in self.f:
            if self.f[e] == max:
                res.append(e)
        return res

my comments:

solution accepted, 95ms run time

from other ppl's solution:

1. could not figure the follow up

2. more organized code:

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        if not root:
            return res
        
        occur = {}
        level = [root]
        
        while level:
            next_level = []
            for node in level:
                if node.val in occur:
                    occur[node.val] += 1
                else:
                    occur[node.val] = 1
                    
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
                    
            level = next_level
        
        max_val = max(occur.values())
        for k,v in occur.iteritems():
            if v == max_val:
                res.append(k)
        
        
        return res