当前位置:   article > 正文

501.二叉搜索树的众数

501.二叉搜索树的众数
  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. ArrayList<Integer> reslist =new ArrayList<>();
  18. int count;
  19. int maxcount;
  20. TreeNode pre;
  21. public int[] findMode(TreeNode root) {
  22. sub_iter(root);
  23. int[] res = new int[reslist.size()];
  24. for(int i=0;i<reslist.size();i++){
  25. res[i] = reslist.get(i);
  26. }
  27. return res;
  28. }
  29. public void sub_iter(TreeNode node){
  30. if(node==null){
  31. return;
  32. }
  33. sub_iter(node.left);
  34. if(pre==null){
  35. count=1;
  36. }else if(pre.val == node.val){
  37. count++;
  38. }else{
  39. count=1;
  40. }
  41. pre = node;
  42. if(count==maxcount) reslist.add(node.val);
  43. if(count>maxcount){
  44. maxcount = count;
  45. reslist.clear();
  46. reslist.add(node.val);
  47. }
  48. sub_iter(node.right);
  49. }
  50. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/882446?site
推荐阅读
相关标签
  

闽ICP备14008679号