LeetCode 501: Find Mode in Binary Search Tree Solution
Master LeetCode problem 501 (Find Mode in Binary Search Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
501. Find Mode in Binary Search Tree
Problem Explanation
Explanation
To find the mode(s) in a binary search tree (BST), we will perform an in-order traversal of the BST while keeping track of the frequency of each element. We will use a hashmap to store the frequency of each element. Then, we will determine the element(s) with the highest frequency (mode) and return them.
- Perform an in-order traversal of the BST to collect the frequency of each element using a hashmap.
- Find the element(s) with the highest frequency (mode).
- Return the mode(s).
Time complexity: O(n) - where n is the number of nodes in the BST. Space complexity: O(n) - for the hashmap to store frequencies.
Solution Code
class Solution {
Map<Integer, Integer> map = new HashMap<>();
int maxFreq = 0;
public int[] findMode(TreeNode root) {
inorder(root);
List<Integer> modes = new ArrayList<>();
for (int key : map.keySet()) {
if (map.get(key) == maxFreq) {
modes.add(key);
}
}
return modes.stream().mapToInt(Integer::intValue).toArray();
}
private void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
map.put(node.val, map.getOrDefault(node.val, 0) + 1);
maxFreq = Math.max(maxFreq, map.get(node.val));
inorder(node.right);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 501 (Find Mode in Binary Search Tree)?
This page provides optimized solutions for LeetCode problem 501 (Find Mode in Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 501 (Find Mode in Binary Search Tree)?
The time complexity for LeetCode 501 (Find Mode in Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 501 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 501 in Java, C++, or Python.