Find Mode in Binary Search Tree
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, 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.
Example 1:
Input: root = [1,null,2,2]
Output: [2]
Example 2:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [1, 104].
-105 <= Node.val <= 105
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
思路一:递归遍历二叉树,用 map 存储节点值
public int[] findMode(TreeNode root) {
modeMap.clear();
findModeRec(root);
int maxCount = 0;
List<Integer> maxValues = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : modeMap.entrySet()) {
if (e.getValue() > maxCount) {
maxCount = e.getValue();
maxValues.clear();
maxValues.add(e.getKey());
} else if (e.getValue() == maxCount) {
maxValues.add(e.getKey());
}
}
return maxValues.stream().mapToInt(Integer::intValue).toArray();
}
private static final Map<Integer, Integer> modeMap = new HashMap<>();
public void findModeRec(TreeNode root) {
if (root == null) {
return;
}
modeMap.compute(root.val, (k, v) -> v == null ? 1 : v + 1);
findModeRec(root.left);
findModeRec(root.right);
}
思路二:看了官方的题解,可以使用中序遍历,中序遍历相当于遍历有序数组
标签:return,modeMap,findModeRec,maxValues,easy,maxCount,root,leetcode,501 From: https://www.cnblogs.com/iyiluo/p/17064610.html