前言
题目: 501. 二叉搜索树中的众数
文档: 代码随想录——二叉搜索树中的众数
编程语言: C++
解题状态: 不会…
思路
利用二叉搜索树性质的同时再加上双指针法。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int maxCount = 0;
int count = 0;
TreeNode* pre = NULL;
vector<int> result;
void searchBST(TreeNode* cur) {
if (!cur) return;
searchBST(root -> 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);
}
searchBST(root -> right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
count = 0;
maxCount = 0;
pre = NULL;
result.clear();
searchBST(root);
return result;
}
};
标签:count,right,TreeNode,cur,val,LeetCode501,众数,树中,left
From: https://blog.csdn.net/daishabby2486/article/details/141220433