https://leetcode.com/problems/find-mode-in-binary-search-tree/

1. Use BST:

  1. //24 ms 20.8 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. vector<int> findMode(TreeNode* root) {
  14. vector<int> result;
  15. int val_ = 0;
  16. int count_ = 0;
  17. int max_count_ = 0;
  18. inorder(root, result, val_, count_, max_count_);
  19. return result;
  20. }
  21. //the mode numbers in the binary tree are all connected
  22. void inorder(TreeNode* root, vector<int>& result, int& val_, int& count_, int& max_count_){
  23. if(!root) return;
  24. inorder(root->left, result, val_, count_, max_count_);
  25. if (count_ > 0 && root->val == val_) {
  26. count_++;
  27. } else {
  28. val_ = root->val;
  29. count_ = 1;
  30. }
  31. if (count_ > max_count_) {
  32. max_count_ = count_;
  33. result.clear();
  34. }
  35. if (count_ == max_count_)
  36. result.push_back(root->val);
  37. inorder(root->right, result, val_, count_, max_count_);
  38. }
  39. };