LeetCode501
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树

  1. class Solution {
  2. TreeNode pre = null;
  3. LinkedList<Integer> list = new LinkedList<>();
  4. int maxCount = 0;
  5. int count = 0;
  6. public int[] findMode(TreeNode root) {
  7. if (root == null) {
  8. return new int[]{};
  9. }
  10. preOrder(root);
  11. int size = list.size();
  12. int[] arr = new int[size];
  13. for (int i = 0; i < size; i++) {
  14. arr[i] = list.get(i);
  15. }
  16. return arr;
  17. }
  18. private void preOrder(TreeNode root) {
  19. if (root == null) {
  20. return;
  21. }
  22. if (root.left != null) {
  23. preOrder(root.left);
  24. }
  25. if (pre == null) {
  26. count = 1;
  27. } else if (pre.val == root.val) {
  28. count++;
  29. } else {
  30. count = 1;
  31. }
  32. pre = root;
  33. if (count == maxCount){
  34. list.addLast(root.val);
  35. }
  36. if (count > maxCount) {
  37. list.clear();
  38. maxCount = count;
  39. list.addLast(root.val);
  40. }
  41. if (root.right != null) {
  42. preOrder(root.right);
  43. }
  44. }
  45. }

参考文献

  1. 501. 【暴力统计】【中序遍历】详解