# 501. Find Mode in Binary Search Tree

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/find-mode-in-binary-search-tree/description/

> 内容描述

```
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).
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******


求出所有node的集合，然后求众数即可

beats 90.44%

```python
class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        res, cur_level = [], [root]
        while cur_level:
            next_level, tmp_res = [], []
            for node in cur_level:
                tmp_res.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            res.extend(tmp_res)
            cur_level = next_level
        c = collections.Counter(res)
        max_freq = max(c.values())
        res = []
        for key in c:
            if c[key] == max_freq:
                res.append(key)
        return res
```
> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

大可以在求点集合的时候inorder遍历，这样我们相当于是升序遍历，那么边遍历可以边算当前数字的freq，并且同时更新max_freq 和更新modes

beats 90.44%

```python
class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        self.modes = []
        self.max_freq = 0
        self.cur_freq = 0
        self.cur_item = None
        if root:
            self.inorder(root)
        return self.modes
    
    def calc_freq(self, value):
        if self.cur_item == value:
            self.cur_freq += 1
        else:
            self.cur_item = value
            self.cur_freq = 1
        if self.cur_freq > self.max_freq:
            self.max_freq = self.cur_freq
            self.modes = [self.cur_item]
        elif self.cur_freq == self.max_freq:
            self.modes.append(value)
    
    def inorder(self, root):
        if root:
            self.inorder(root.left)
            self.calc_freq(root.val)
            self.inorder(root.right)
```































