1. Description
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e, the most frequnetly occured element) in it.
If the tree has more than one node, return them in any order.
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.
constraints :
- The number of nodes in the tree is in the range [1, \(10^{4}\)].
- \(-10^{5}\) <= Node.val <= \(10^{5}\)
2. Algorithms
- Start
- Declare variable named freq_table and initialize to empty dictionary.
- Declare function named helper which get root as input.
- If root have value, traverse left subtree and right subtree recursively.
- If the value of root is in frequency_table, increment its value as 1.
- Else, Initialize its value as 1.
- Make frequency table by operating helepr function.
- Calculate max value from frequency table's values.
- Extract keys which its value is same with max_value and store them into list.
- End
3. Codes
# Definition for a binary tree node.
# 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]:
freq_table = {}
def helper(root) :
nonlocal freq_table
if root :
if root.val in freq_table :
freq_table[root.val] += 1
else :
freq_table[root.val] = 1
helper(root.left)
helper(root.right)
helper(root)
max_value = max(freq_table.values())
return [k for k, v in freq_table.items() if v == max_value]
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
506 Relative Ranks (0) | 2022.09.03 |
---|---|
504 Base 7 (0) | 2022.09.02 |
500 Keyboard Row (0) | 2022.09.02 |
496 Next Greater Element I (0) | 2022.09.01 |
495 Teemo Attacking (0) | 2022.09.01 |