解法一:中序遍历

总感觉进阶要求有点奇怪。。。按照进阶要求,那么就不用map来保存频率了,二叉搜索树进行中序遍历可以按升序访问,值相同的结点会连续访问。在访问过程中记录最高频率的结点,并记录上一次访问结点的值及其出现频率,根据频率大小不断更新保存答案的数组。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. private List<Integer> ansList;
  12. // 最高出现频率
  13. private int maxTimes;
  14. // 当前出现频率
  15. private int curTimes;
  16. // 上次被访问结点的值
  17. private int lastVal;
  18. public int[] findMode(TreeNode root) {
  19. ansList = new ArrayList<>();
  20. lastVal = -1;
  21. maxTimes = curTimes = 0;
  22. inOrder(root);
  23. int[] ans = new int[ansList.size()];
  24. for (int i = 0; i < ans.length; ++i) {
  25. ans[i] = ansList.get(i);
  26. }
  27. return ans;
  28. }
  29. private void inOrder(TreeNode root) {
  30. if (root == null) {
  31. return;
  32. }
  33. inOrder(root.left);
  34. if (root.val == lastVal) {
  35. ++curTimes;
  36. } else {
  37. curTimes = 1;
  38. lastVal = root.val;
  39. }
  40. if (curTimes > maxTimes) {
  41. ansList.clear();
  42. maxTimes = curTimes;
  43. ansList.add(lastVal);
  44. } else if (curTimes == maxTimes) {
  45. ansList.add(lastVal);
  46. }
  47. inOrder(root.right);
  48. }
  49. }