<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href="https://en.wikipedia.org/wiki/Mode_(statistics)" target="_blank">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p>

<p>If the tree has more than one mode, return them in <strong>any order</strong>.</p>

<p>Assume a BST is defined as follows:</p>

<ul>
	<li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li>
	<li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li>
	<li>Both the left and right subtrees must also be binary search trees.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg" style="width: 142px; height: 222px;" />
<pre>
<strong>Input:</strong> root = [1,null,2,2]
<strong>Output:</strong> [2]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> root = [0]
<strong>Output:</strong> [0]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
from collections import defaultdict
from typing import List, Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        def in_order_traversal(node):
            if not node:
                return
            in_order_traversal(node.left)
            values.append(node.val)
            in_order_traversal(node.right)
        
        if not root:
            return []
        
        # Step 1: Perform in-order traversal to get sorted values
        values = []
        in_order_traversal(root)
        
        # Step 2: Count frequencies
        count = defaultdict(int)
        for value in values:
            count[value] += 1
        
        # Step 3: Find the maximum frequency
        max_freq = max(count.values())
        
        # Step 4: Collect all values with the maximum frequency
        modes = [key for key, freq in count.items() if freq == max_freq]
        
        return modes

# Example usage
if __name__ == "__main__":
    # Example 1
    root1 = TreeNode(1)
    root1.right = TreeNode(2)
    root1.right.right = TreeNode(2)
    
    # Example 2
    root2 = TreeNode(0)

    solution = Solution()
    print(solution.findMode(root1))  # Output: [2]
    print(solution.findMode(root2))  # Output: [0]

20000