package notsubmit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class FindMode {
private Map<Integer, Integer> freqMap = new HashMap();
public int[] findMode(TreeNode root) {
if(root == null) {
return null;
}
TreeNode cur = root;
TreeNode mostRight = null;
while(cur != null) {
if(cur.left == null) {
int preNum = freqMap.get(cur.val) == null ? 0 : freqMap.get(cur.val);
freqMap.put(cur.val, ++preNum);
cur = cur.right;
}else {
mostRight = getMostRight(cur);
if(mostRight.right == null) {
mostRight.right = cur;
cur = cur.left;
}else {
countFreq(cur.val);
mostRight.right = null;
cur = cur.right;
}
}
}
ArrayList<Integer> ansList = new ArrayList<Integer>();
int maxVal = -1;
for(Integer k: freqMap.keySet()) {
int val = freqMap.get(k);
if(maxVal == -1) {
ansList.add(k);
maxVal = val;
continue;
}else if(val > maxVal){
ansList.clear();
maxVal = val;
ansList.add(k);
}else if(val == maxVal) {
ansList.add(k);
}
}
int[] ans = new int[ansList.size()];
for(int i=0; i < ansList.size(); ++i) {
ans[i] = ansList.get(i);
}
return ans;
}
public TreeNode getMostRight(TreeNode head) {
TreeNode node = head.left;
while(node.right != null && node.right != head) {
node = node.right;
}
return node;
}
public void countFreq(int val) {
int preNum = freqMap.get(val) == null ? 0 : freqMap.get(val);
freqMap.put(val, ++preNum);
}
public static void main(String[] args) {
}
}