501. 二叉搜索树中的众数

image.png

中序递归

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. TreeNode pre ;
  18. int count ; //统计频率
  19. int maxCount; //最大频率
  20. List<Integer> resL = new ArrayList<>();
  21. public int[] findMode(TreeNode root) {
  22. count = 0;
  23. maxCount = 0;
  24. pre = null;
  25. resL.clear();
  26. searchBST(root);
  27. int size = resL.size();
  28. int [] res = new int[ size];
  29. for(int i = 0 ; i < size; i++ ) {
  30. res[i] = resL.get(i);
  31. }
  32. return res;
  33. }
  34. public void searchBST(TreeNode cur ) {
  35. if(cur == null ) return;
  36. searchBST(cur.left); //左
  37. if(pre == null) { //第一个节点
  38. count = 1;
  39. } else if(pre.val == cur.val) { // 与前一个节点数值相同
  40. count ++;
  41. } else {
  42. count = 1; // 与前一个节点数值不同
  43. }
  44. pre = cur;
  45. if(count == maxCount ) { // 如果和最大值相同,放进resL中
  46. resL.add(cur.val);
  47. }
  48. if(count > maxCount ) {
  49. resL.clear(); // 很关键的一步,不要忘记清空result,之前result里的元素都失效了
  50. resL.add(cur.val);
  51. maxCount = count; // 更新最大频率
  52. }
  53. searchBST(cur.right);
  54. return ;
  55. }
  56. }

迭代

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public int[] findMode(TreeNode root) {
  18. if(root == null ) return new int[0];
  19. //迭代 中序
  20. Stack<TreeNode> stack = new Stack<>();
  21. TreeNode pre = null;
  22. TreeNode cur = root;
  23. int cnt = 0;
  24. int maxCnt = 0;
  25. List<Integer> list = new ArrayList<>();
  26. while( cur != null || !stack.isEmpty() ) {
  27. if(cur != null ) { //左
  28. stack.push(cur);
  29. cur = cur.left;
  30. } else {
  31. cur = stack.pop();
  32. if(pre == null ) {
  33. cnt = 1;
  34. } else if(pre.val == cur.val ) {
  35. cnt++;
  36. } else {
  37. cnt = 1;
  38. }
  39. if(cnt == maxCnt ) {
  40. list.add(cur.val);
  41. } else if(cnt > maxCnt ) {
  42. list.clear();
  43. maxCnt = cnt;
  44. list.add(cur.val);
  45. }
  46. pre = cur;
  47. cur = cur.right; //右
  48. }
  49. }
  50. int size = list.size();
  51. int[] res = new int[size];
  52. for(int i = 0; i < size; i++ ) {
  53. res[i] = list.get(i);
  54. }
  55. return res;
  56. }
  57. }