解法一:中序遍历
总感觉进阶要求有点奇怪。。。按照进阶要求,那么就不用map来保存频率了,二叉搜索树进行中序遍历可以按升序访问,值相同的结点会连续访问。在访问过程中记录最高频率的结点,并记录上一次访问结点的值及其出现频率,根据频率大小不断更新保存答案的数组。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> ansList;
// 最高出现频率
private int maxTimes;
// 当前出现频率
private int curTimes;
// 上次被访问结点的值
private int lastVal;
public int[] findMode(TreeNode root) {
ansList = new ArrayList<>();
lastVal = -1;
maxTimes = curTimes = 0;
inOrder(root);
int[] ans = new int[ansList.size()];
for (int i = 0; i < ans.length; ++i) {
ans[i] = ansList.get(i);
}
return ans;
}
private void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
if (root.val == lastVal) {
++curTimes;
} else {
curTimes = 1;
lastVal = root.val;
}
if (curTimes > maxTimes) {
ansList.clear();
maxTimes = curTimes;
ansList.add(lastVal);
} else if (curTimes == maxTimes) {
ansList.add(lastVal);
}
inOrder(root.right);
}
}