目錄
- 題目
- 1、不考慮BTS性質,直接尋找眾數集合(利用map)
- 2、考慮BTS的中序遍歷結果性質
題目
給定一個有相同值的二叉搜索樹(BST),找出 BST 中的所有眾數(出現頻率最高的元素)。
假定 BST 有如下定義:
結點左子樹中所含結點的值小于等于當前結點的值
結點右子樹中所含結點的值大于等于當前結點的值
左子樹和右子樹都是二叉搜索樹
1、不考慮BTS性質,直接尋找眾數集合(利用map)
這種方法沒有考慮性質,同時消耗了額外的空間。
同時要注意,按照value值排序是沒有內置函數的,得先將map轉換為vector,然后自定義sort的規則,對pair類型數據的第二個值按照從大到小進行排序。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
private:void traversal(TreeNode* cur,unordered_map<int,int>& map){if(cur == NULL ) return ;//以結點值為key,結點值出現的頻次為map值map[cur->val]++;traversal(cur->left,map);traversal(cur->right,map);return ;}//定義sort排序的規則,以二維數組的第二維從大到小排序bool static cmp(const pair<int,int>& a,const pair<int,int>& b){if(a.second>b.second) return 1;else return 0;}
public:vector<int> findMode(TreeNode* root) {unordered_map<int,int> map;vector<int> result;if(root == NULL) return result;traversal(root,map);//將map轉化為vector(二維數組),以便于下一步的排序vector<pair<int,int>> vec(map.begin(),map.end());sort(vec.begin(),vec.end(),cmp);//vec第一個元素是頻次最高的,然后繼續尋找與之頻次一樣的元素for(int i=0;i<vec.size();i++){if(vec[i].second == vec[0].second) result.push_back(vec[i].first);else break;}return result;}
};
2、考慮BTS的中序遍歷結果性質
中序遍歷的結果是遞增的,所以我們只需要比較此結點與上結點是否相等,從而累加頻次,然后更新最大頻次,更新結果數組,保證眾數集合就行了。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
private:int MaxCount;int count;TreeNode* pre = NULL;vector<int> result;void traversal(TreeNode* cur){if(cur == NULL ) return;traversal(cur->left);if(pre == NULL){count = 1;}else if(pre->val == cur->val){count++;}else{count = 1;}pre = cur;//如果出現次數也是最大次數,說明此元素也屬于眾數集合,應當加入結果集if(count == MaxCount) result.push_back(cur->val);//如果最大次數被更新,那么得清除舊結果if(count > MaxCount){MaxCount = count;result.clear();result.push_back(cur->val);}traversal(cur->right);return ;}
public:vector<int> findMode(TreeNode* root) {MaxCount = 0;count = 0;pre = NULL;result.clear();traversal(root);return result;}
};