Last active
January 29, 2017 10:36
-
-
Save Chen-tao/451494df077e4b7fde51030c127ad8f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.