Skip to content

Instantly share code, notes, and snippets.

@Chen-tao
Last active January 29, 2017 10:36
Show Gist options
  • Save Chen-tao/451494df077e4b7fde51030c127ad8f2 to your computer and use it in GitHub Desktop.
Save Chen-tao/451494df077e4b7fde51030c127ad8f2 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
public static int[] findMode(TreeNode root) {
aMap.clear();
if (root == null) {
return null;
}
getMode(root);
int idx = 0;
int max = 0;
for (int i : aMap.keySet()) {
if (aMap.get(i) >= max) {
max = aMap.get(i);
}
}
List<Integer> al = new ArrayList<Integer>();
for (int i : aMap.keySet()) {
if (aMap.get(i) == max) {
al.add(i);
}
}
int[] ansi = new int[al.size()];
for (int i = 0; i < al.size(); i++) {
ansi[i] = al.get(i);
}
return ansi;
}
private static void getMode(TreeNode root) {
if (root == null) {
return;
}
if (aMap.containsKey(root.val)) {
int c = aMap.get(root.val);
aMap.put(root.val, ++c);
} else {
aMap.put(root.val, 1);
}
getMode(root.right);
getMode(root.left);
}
}
@Chen-tao
Copy link
Author

Given a binary tree with duplicates. You have to find all the mode(s) in given binary tree.

For example:
Given binary tree [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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment