[leetcode]501. Find Mode in Binary Search Tree
Analysis
讨厌的人总是那么讨厌!—— [ummmm~]
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.
寻找二叉树中的众数,然后这道题中的二叉树子节点是小于等于父节点的,但是一般情况下二叉树的子节点是严格小于父节点的。
Implement
方法一(用一个hash表记录所有数值的出现次数,然后输出出现次数最多的数值,这里空间复杂度用了格外的O(N))
/**
* 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 {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int max_cnt = 0;
map<int, int> vals;
preOrder(root, max_cnt, vals);
for(auto v:vals){
if(v.second == max_cnt)
res.push_back(v.first);
}
return res;
}
void preOrder(TreeNode* root, int& max_cnt, map<int, int>& vals){
if(!root)
return ;
max_cnt = max(max_cnt, ++vals[root->val]);
preOrder(root->left, max_cnt, vals);
preOrder(root->right, max_cnt, vals);
}
};
方法二(网上大神的做法没有用格外的空间)
/**
* 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 {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int max_cnt = 0;
int cnt = 1;
TreeNode* pre = NULL;
inOrder(root, cnt, pre, max_cnt, res);
return res;
}
void inOrder(TreeNode* root, int& cnt, TreeNode*& pre, int& max_cnt, vector<int>& res){
if(!root)
return ;
inOrder(root->left, cnt, pre, max_cnt, res);
if(pre){
if(pre->val == root->val)
cnt++;
else
cnt = 1;
}
if(cnt >= max_cnt){
if(cnt > max_cnt) res.clear();
res.push_back(root->val);
max_cnt = cnt;
}
pre = root;
inOrder(root->right, cnt, pre, max_cnt, res);
}
};