Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/501.html
501. Find Mode in Binary Search Tree
Level
Easy
Description
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
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.
For example:
Given BST [1,null,2,2]
,
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Solution
First do breadth first search on the binary tree to find each value’s number of occurrences. Then find the maximum number of occurrences and the numbers that have the maximum number of occurrences.
-
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int[] findMode(TreeNode root) { if (root == null) return new int[0]; Map<Integer, Integer> countsMap = new HashMap<Integer, Integer>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); int value = node.val; int count = countsMap.getOrDefault(value, 0); count++; countsMap.put(value, count); TreeNode left = node.left, right = node.right; if (left != null) queue.offer(left); if (right != null) queue.offer(right); } int maxCount = 0; Map<Integer, List<Integer>> countValuesMap = new HashMap<Integer, List<Integer>>(); Set<Integer> valuesSet = countsMap.keySet(); for (int value : valuesSet) { int count = countsMap.get(value); maxCount = Math.max(maxCount, count); List<Integer> values = countValuesMap.getOrDefault(count, new ArrayList<Integer>()); values.add(value); countValuesMap.put(count, values); } List<Integer> maxCountValues = countValuesMap.get(maxCount); int length = maxCountValues.size(); int[] modes = new int[length]; for (int i = 0; i < length; i++) modes[i] = maxCountValues.get(i); return modes; } }
-
// OJ: https://leetcode.com/problems/find-mode-in-binary-search-tree/ // Time: O(N) // Space: O(N) class Solution { public: vector<int> findMode(TreeNode* root) { vector<int> ans; unordered_map<int, int> m; int maxFreq = 0; function<void(TreeNode*)> dfs = [&](TreeNode *root) { if (!root) return; int f = ++m[root->val]; if (f > maxFreq) maxFreq = f, ans = {root->val}; else if (f == maxFreq) ans.push_back(root->val); dfs(root->left); dfs(root->right); }; dfs(root); return ans; } };
-
# 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: TreeNode) -> List[int]: def dfs(root): if root is None: return nonlocal mx, prev, ans, cnt dfs(root.left) cnt = cnt + 1 if prev == root.val else 1 if cnt > mx: ans = [root.val] mx = cnt elif cnt == mx: ans.append(root.val) prev = root.val dfs(root.right) prev = None mx = cnt = 0 ans = [] dfs(root) return ans ############ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findMode(self, root): """ :type root: TreeNode :rtype: List[int] """ def visit(v): if v != self.pre: self.pre = v self.cnt = 0 self.cnt += 1 if self.cnt > self.maxFreq: self.maxFreq = self.cnt self.modeCnt = 1 elif self.cnt == self.maxFreq: if self.ans: self.ans[self.modeCnt] = v self.modeCnt += 1 def inorder(root): if root: inorder(root.left) visit(root.val) inorder(root.right) self.pre = None self.ans = None self.maxFreq = self.modeCnt = self.cnt = 0 inorder(root) self.ans = [0] * self.modeCnt self.modeCnt = self.cnt = 0 inorder(root) return self.ans
-
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findMode(root *TreeNode) []int { mx, cnt := 0, 0 var prev *TreeNode var ans []int var dfs func(root *TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) if prev != nil && prev.Val == root.Val { cnt++ } else { cnt = 1 } if cnt > mx { ans = []int{root.Val} mx = cnt } else if cnt == mx { ans = append(ans, root.Val) } prev = root dfs(root.Right) } dfs(root) return ans }