[leetcode]: 501. Find Mode in Binary Search Tree

红太狼 2022-06-15 05:26 256阅读 0赞

1.题目

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],

  1. 1
  2. \
  3. 2
  4. /
  5. 2

return [2].

给一棵二叉搜索树,有重复元素。找出其中重复次数最多的元素。如果有多个重复次数一样的元素,则放在一个列表中作为返回结果。

2.分析

这题考察的是BST的中序遍历,中序遍历的元素是有序的,在遍历的过程中统计元素出现的次数即可。

3.代码

中序遍历–迭代

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<int> findMode(TreeNode* root) {
  13. vector<int> mode;
  14. if (root == NULL)
  15. return mode;
  16. int max_c = -1;//记录历史最多出现次数
  17. int last_v = INT_MIN;
  18. int count = 1;//当前值出现的次数
  19. stack<TreeNode*> nodes;
  20. while (!nodes.empty() || root) {
  21. if (root) {
  22. nodes.push(root);
  23. root = root->left;//先遍历到左子树最下边
  24. }
  25. else {
  26. root = nodes.top();
  27. nodes.pop();
  28. if (last_v != INT_MIN) {
  29. if (root->val == last_v)
  30. ++count;
  31. else
  32. count = 1;
  33. }
  34. if (count > max_c)
  35. {
  36. max_c = count;
  37. mode.erase(mode.begin(), mode.end());
  38. mode.push_back(root->val);
  39. }
  40. else if (count == max_c)
  41. mode.push_back(root->val);
  42. last_v = root->val;
  43. root = root->right;//转到右子树
  44. }
  45. }
  46. return mode;
  47. }
  48. };

中序遍历–递归

  1. class Solution {
  2. public:
  3. void inOrder(TreeNode* root, vector<int>&mode,int& val,int& count,int& maxc) {
  4. if (root == NULL)
  5. return;
  6. inOrder(root->left,mode,val,count,maxc);
  7. if (val != INT_MIN) {
  8. if (val == root->val)
  9. ++count;
  10. else
  11. count = 1;
  12. }
  13. if (count > maxc) {
  14. maxc = count;
  15. mode.erase(mode.begin(), mode.end());//出现次数更多的元素,清空容器
  16. mode.push_back(root->val);
  17. }
  18. else if (count == maxc)
  19. mode.push_back(root->val);
  20. val = root->val;
  21. inOrder(root->right, mode, val, count, maxc);
  22. }
  23. vector<int> findMode(TreeNode* root) {
  24. vector<int> mode;
  25. if (root == NULL)
  26. return mode;
  27. int maxc = -1;
  28. int count = 1;
  29. int val = INT_MIN;
  30. inOrder(root, mode, val, count, maxc);
  31. return mode;
  32. }
  33. };

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读