1+ """
2+ Time: O(N). For we traverse every node recursively.
3+ Space: O(N). Becuase we store all element's val and count in `counter`.
4+ Note that, we do not use the feature of BST.
5+ """
16from collections import Counter
27class Solution (object ):
38 def findMode (self , root ):
@@ -14,11 +19,21 @@ def count(node):
1419 return [val for val , count in counter .items () if count == max_count ]
1520
1621"""
17- Time: O(N). For we traverse every node recursively.
18- Space: O(N). Becuase we store all element's val and count in `counter`.
19- Note that, we do not use the feature of BST.
20- """
22+ To use the feature of BST, we are going to inorder traverse the BST.
23+ So it will be like we are iterating a sorted array.
24+
25+ [1]
26+ While iterating, we can put only the element count that is greater or equal than `max_count` to `ans`.
27+ If we encounter a new element with larger `curr_count`, we reset the `ans`.
2128
29+ [0]
30+ With the help of `prev_val` we can know that `curr_node` is the same to the previous or not.
31+ If not, its a new element, we need to reset the `curr_count`.
32+
33+ Time: O(N). Space: O(LogN)
34+
35+ For better understanding, below is a template for inorder traverse.
36+ """
2237class Solution (object ):
2338 def findMode (self , root ):
2439 if not root : return []
@@ -54,23 +69,6 @@ def findMode(self, root):
5469
5570 return ans
5671
57- """
58- To use the feature of BST, we are going to inorder traverse the BST.
59- So it will be like we are iterating a sorted array.
60-
61- [1]
62- While iterating, we can put only the element count that is greater or equal than `max_count` to `ans`.
63- If we encounter a new element with larger `curr_count`, we reset the `ans`.
64-
65- [0]
66- With the help of `prev_val` we can know that `curr_node` is the same to the previous or not.
67- If not, its a new element, we need to reset the `curr_count`.
68-
69- Time: O(N). Space: O(LogN)
70-
71- For better understanding, below is a template for inorder traverse.
72- """
73-
7472#inorder traversal of BST
7573def inorder_traverse (root ):
7674 curr = root
@@ -85,3 +83,28 @@ def inorder_traverse(root):
8583 print curr .val
8684
8785 curr = curr .right
86+
87+
88+
89+
90+ """
91+ Time: O(N)
92+ Space: O(N)
93+ """
94+ class Solution (object ):
95+ def findMode (self , root ):
96+ def helper (node ):
97+ if not node : return
98+ counter [node .val ] += 1
99+ counter ['maxCount' ] = max (counter ['maxCount' ], counter [node .val ])
100+ helper (node .left )
101+ helper (node .right )
102+
103+ ans = []
104+ counter = collections .Counter ()
105+ helper (root )
106+ for v in counter :
107+ if v != 'maxCount' and counter [v ]== counter ['maxCount' ]:
108+ ans .append (v )
109+
110+ return ans
0 commit comments