Skip to content

Commit 6661605

Browse files
committed
Sync LeetCode submission Runtime - 55 ms (14.43%), Memory - 20.8 MB (5.13%)
1 parent 55cff60 commit 6661605

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<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>
2+
3+
<p>If the tree has more than one mode, return them in <strong>any order</strong>.</p>
4+
5+
<p>Assume a BST is defined as follows:</p>
6+
7+
<ul>
8+
<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>
9+
<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>
10+
<li>Both the left and right subtrees must also be binary search trees.</li>
11+
</ul>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg" style="width: 142px; height: 222px;" />
16+
<pre>
17+
<strong>Input:</strong> root = [1,null,2,2]
18+
<strong>Output:</strong> [2]
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> root = [0]
25+
<strong>Output:</strong> [0]
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
33+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
34+
</ul>
35+
36+
<p>&nbsp;</p>
37+
<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).
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Approach 1: Count Frequency with Hash Map (DFS)
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
# Definition for a binary tree node.
7+
# class TreeNode:
8+
# def __init__(self, val=0, left=None, right=None):
9+
# self.val = val
10+
# self.left = left
11+
# self.right = right
12+
13+
from collections import defaultdict
14+
15+
class Solution:
16+
def findMode(self, root: Optional[TreeNode]) -> List[int]:
17+
def dfs(node, counter):
18+
if not node:
19+
return
20+
21+
counter[node.val] += 1
22+
dfs(node.left, counter)
23+
dfs(node.right, counter)
24+
25+
counter = defaultdict(int)
26+
dfs(root, counter)
27+
max_freq = max(counter.values())
28+
29+
ans = []
30+
for key in counter:
31+
if counter[key] == max_freq:
32+
ans.append(key)
33+
34+
return ans
35+

0 commit comments

Comments
 (0)