Skip to content

Instantly share code, notes, and snippets.

@leearmee35
Created February 20, 2017 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leearmee35/dbe313ce7a5d6e9144840f968e3108b8 to your computer and use it in GitHub Desktop.
Save leearmee35/dbe313ce7a5d6e9144840f968e3108b8 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 {
private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
private int max = 0;
public int[] findMode(TreeNode root) {
if(root==null) return new int[0];
helper(root);
List<Integer> list = new LinkedList<>();
for(int key: map.keySet()){
if(map.get(key) == max) list.add(key);
}
int[] res = new int[list.size()];
for(int i = 0; i<res.length; i++) res[i] = list.get(i);
return res;
}
public void helper(TreeNode node){
map.put(node.val, map.getOrDefault(node.val, 0)+1);
max = Math.max(map.get(node.val), max);
if(node.left!=null){
helper(node.left);
}
if(node.right!=null){
helper(node.right);
}
}
}
@TLiu2014
Copy link

TLiu2014 commented Jul 4, 2017

This solution used a Hash map, which requires additional spaces and is not allowed by the question, LeetCode 501. Find Mode in Binary Search Tree.

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