题目描述
原题链接:501. 二叉搜索树中的众数
解题思路
一、递归法
(1)双指针方法
设置一个指针pre
指向前一个遍历结点,另一个指针root
指向当前遍历结点。设置一个变量count
记录,当前等于该结点数值的结点个数。maxCount
记录众数。
/**
* 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 {
public:
TreeNode* pre = NULL;
int count = 1, maxCount = 1;
vector<int> res;
vector<int> findMode(TreeNode* root) {
if(!root) return res;
// 左
findMode(root->left);
// 中
// 当pre为空或pre与root指向元素的值不相等,则让当前count=1。若二者指向相等,则count++
if(!pre || pre->val != root->val) count = 1;
else if(pre->val == root->val) count++;
// 更新pre指针
pre = root;
// 当找到的这个元素个数与之前添加过的最大元素个数相同,则添加。若更大清空原来存储结果,加入新结果
if(count == maxCount) res.push_back(root->val);
else if(count > maxCount) {
maxCount = count;
res.clear();
res.push_back(root->val);
}
// 右
findMode(root->right);
return res;
}
};
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.pre = None
self.count = 1
self.max_count = -1
self.nodes = []
def findMode(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return self.nodes
self.findMode(root.left)
if not self.pre or self.pre.val != root.val:
self.count = 1
if self.pre and self.pre.val == root.val:
self.count += 1
self.pre = root
if self.count == self.max_count:
self.nodes.append(root.val)
elif self.count > self.max_count:
self.max_count = self.count
self.nodes.clear()
self.nodes.append(root.val)
self.findMode(root.right)
return self.nodes
(2)哈希表法
设置一个向量path
,按中序遍历将结点存入其中。设置一个哈希表record
统计各值出现的次数,用maxCount
获取最大次数。最后将与出现最大次数相同的数加入到结果集中。
/**
* 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 {
public:
// 用path按中序遍历顺序记录结点
vector<int> path;
void traversal(TreeNode* root) {
if(!root) return ;
traversal(root->left);
path.push_back(root->val);
traversal(root->right);
}
vector<int> findMode(TreeNode* root) {
vector<int> res;
traversal(root);
// 记录各值出现频率
unordered_map<int, int> record;
for(int num : path) {
record[num]++;
}
// 获取最大次数值
int maxCount = 1;
for(auto it = record.begin(); it != record.end(); it++) {
if(it->second > maxCount) maxCount = it->second;
}
// 将众数添加大结果集
for(auto it = record.begin(); it != record.end(); it++) {
if(it->second == maxCount) res.push_back(it->first);
}
return res;
}
};
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.freq_map = defaultdict(int)
def searchBST(self, root):
if not root:
return
self.searchBST(root.left)
self.freq_map[root.val] += 1
self.searchBST(root.right)
return
def findMode(self, root: Optional[TreeNode]) -> List[int]:
self.searchBST(root)
res = []
max_value = max(self.freq_map.values())
for k, v in self.freq_map.items():
if v == max_value:
res.append(k)
return res
二、迭代法
/**
* 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 {
public:
vector<int> findMode(TreeNode* root) {
int count = 1, maxCount = 1;
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* pre = NULL;
vector<int> res;
while(cur || !st.empty()) {
while(cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top(); st.pop();
// 更新count
if(!pre || pre->val != cur->val)
count = 1;
else if(pre->val == cur->val)
count++;
// 根据count和maxCount比较,选择是否加入结果集
if(count == maxCount)
res.push_back(cur->val);
else if(maxCount < count) {
res.clear();
res.push_back(cur->val);
maxCount = count;
}
pre = cur;
cur = cur->right;
}
return res;
}
};
Python
结合字典的方式
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
cur = root
st = []
freq_map = defaultdict(int)
while cur or len(st) != 0:
while cur:
st.append(cur)
cur = cur.left
cur = st.pop()
freq_map[cur.val] += 1
cur = cur.right
res = []
max_value = max(freq_map.values())
for k, v in freq_map.items():
if v == max_value:
res.append(k)
return res
参考文章:501.二叉搜索树中的众数