Find Mode in Binary Search Tree
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],
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
解析
找到二叉树中的众数。
解法1:inorder(递归)
递归中序遍历二叉树,建立一个哈希表,保存一个最大个数。
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int mx = 0;
unordered_map<int, int> m;
inorder(root, m, mx);
for (auto a : m) {
if (a.second == mx) {
res.push_back(a.first);
}
}
return res;
}
void inorder(TreeNode* root, unordered_map<int, int>& m, int& mx){
if(!root) return;
inorder(root->left, m, mx);
m[root->val] ++;
mx = max(mx, m[root->val]);
inorder(root->right, m, mx);
}
};
解法2:inorder(迭代)
迭代中序遍历二叉树,建立一个哈希表,保存一个最大个数。
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if(!root) return {};
vector<int> res;
int mx = 0;
unordered_map<int, int> m;
stack<TreeNode*> s;
TreeNode* p = root;
while(!s.empty() || p){
while(p){
s.push(p);
p = p->left;
}
p = s.top();
s.pop();
m[p->val] ++;
mx = max(mx, m[p->val]);
p = p->right;
}
for (auto a : m) {
if (a.second == mx) {
res.push_back(a.first);
}
}
return res;
}
};
解法3:inorder(递归不使用额外空间)
利用二叉树的中序遍历有序的特性,对二叉树递归中序遍历,设置一个pre节点,一个count记录当前节点次数,当pre不为空时,不是第一个节点,与前一个节点值比较,如果相等则count+1,否则count=1;
当count大于最大次数mx时,清空res,加入当前节点,并将mx=count;pre更新为当前节点p。
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int mx = 0;
int count = 1;
TreeNode* pre = NULL;
inorder(root, pre, count, mx, res);
return res;
}
void inorder(TreeNode* p, TreeNode*& pre, int& count,int& mx, vector<int>& res){
if(!p) return;
inorder(p->left, pre, count,mx,res);
if(pre){
count = (pre->val == p->val) ? count+1:1;
}
if(count>=mx){
if(count>mx) res.clear();
res.push_back(p->val);
mx = count;
}
pre = p;
inorder(p->right, pre, count,mx,res);
}
};
解法4:inorder(迭代不使用额外空间)
迭代中序遍历,类似于解法3
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if(!root) return {};
vector<int> res;
int mx = 0;
int count =1;
stack<TreeNode*> s;
TreeNode* p = root;
TreeNode* pre = NULL;
while(!s.empty() || p){
while(p){
s.push(p);
p = p->left;
}
p = s.top();s.pop();
if(pre){
count = (pre->val == p->val) ? count+1:1;
}
if(count>=mx){
if(count>mx) res.clear();
res.push_back(p->val);
mx = count;
}
pre = p;
p = p->right;
}
return res;
}
};