501. Find Mode in Binary Search Tree
Easy
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).
package leetcode.easy; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode * left; TreeNode right; TreeNode(int x) { val = x; } } */ public class FindModeInBinarySearchTree { private static void print_arr(int[] nums) { for (int num : nums) { System.out.print(num + " "); } System.out.println(); } java.util.Map<Integer, Integer> map; int max = 0; public int[] findMode(TreeNode root) { this.map = new java.util.HashMap<>(); inorder(root); java.util.List<Integer> list = new java.util.LinkedList<>(); for (int key : map.keySet()) { if (map.get(key) == max) { list.add(key); } } int[] num = new int[list.size()]; for (int i = 0; i < list.size(); i++) { num[i] = list.get(i); } return num; } public void inorder(TreeNode root) { if (root == null) { return; } map.put(root.val, map.getOrDefault(root.val, 0) + 1); if (map.get(root.val) > max) { max = map.get(root.val); } inorder(root.left); inorder(root.right); } @org.junit.Test public void test() { TreeNode tn11 = new TreeNode(1); TreeNode tn22 = new TreeNode(2); TreeNode tn33 = new TreeNode(2); tn11.left = null; tn11.right = tn22; tn22.left = tn33; tn22.right = null; tn33.left = null; tn33.right = null; print_arr(findMode(tn11)); } }