【谷歌面试题】找出二叉查找树中出现频率最高的元素 - 计算机的艺术 - 博客频道 - CSDN.NET
找出二叉查找树中出现频率最高的元素。树中结点满足left->val <= root->val <= right->val。如果多个元素出现次数相等,返回最小的元素。
在一个有序数组中,我们查找出现频率最高的元素,很简单,顺序扫描一遍即可统计出。那么我们对二叉查找树也可以用类似方式统计,因为中序遍历序列就是有序序列,所以我们在中序遍历的过程中就可以统计出出现频率最高的元素。
http://shibaili.blogspot.com/2015/06/google-interview-questions.html
找出二叉查找树中出现频率最高的元素。树中结点满足left->val <= root->val <= right->val。如果多个元素出现次数相等,返回最小的元素。
在一个有序数组中,我们查找出现频率最高的元素,很简单,顺序扫描一遍即可统计出。那么我们对二叉查找树也可以用类似方式统计,因为中序遍历序列就是有序序列,所以我们在中序遍历的过程中就可以统计出出现频率最高的元素。
http://shibaili.blogspot.com/2015/06/google-interview-questions.html
struct
TreeNode{
int
val;
TreeNode *left;
TreeNode *right;
TreeNode(
int
val) {
this
->val = val;
}
};
void
countNodesHelper(TreeNode *root, TreeNode *&pre,
int
&count,
int
&maxCount) {
if
(root == NULL)
return
;
countNodesHelper(root->left,pre,count,maxCount);
if
(pre == NULL) {
pre = root;
count = 1;
}
else
{
if
(pre->val == root->val) {
count++;
if
(maxCount < count) {
maxCount = count;
}
}
else
{
count = 1;
}
}
pre = root;
countNodesHelper(root->right,pre,count,maxCount);
}
int
countNodes(TreeNode *root) {
int
maxCount = 0,count = 0;
TreeNode *pre = NULL;
foo(root,pre,count,maxCount);
return
maxCount;
}
- class TreeNode
- {
- public:
- int val;
- TreeNode *left;
- TreeNode *right;
- TreeNode(int val, TreeNode* left = NULL, TreeNode *right = NULL)
- {
- this->val = val;
- this->left = left;
- this->right = right;
- }
- };
- int GetMostFrequently(TreeNode * root)
- {
- void _GetMostFrequently(TreeNode *root, int & current, int & currentFrequency,
- int & maxFrequency, int & mostFrequently);
- if(root == NULL)
- throw new invalid_argument("Can't be a NULL tree");
- int mostFrequently = INT_MAX;
- int current = INT_MAX;
- int currentFrequency = 0;
- int maxFrequency = 0;
- _GetMostFrequently(root, current, currentFrequency, maxFrequency, mostFrequently);
- return mostFrequently;
- }
- void _GetMostFrequently(TreeNode *root, int & current, int & currentFrequency,
- int & maxFrequency, int & mostFrequently)
- {
- if(root == NULL)
- return;
- _GetMostFrequently(root->left, current, currentFrequency,
- maxFrequency, mostFrequently);
- if(root->val == current)
- ++currentFrequency;
- else
- {
- current = root->val;
- currentFrequency = 1;
- }
- if(currentFrequency > maxFrequency)
- {
- maxFrequency = currentFrequency;
- mostFrequently = current;
- }
- _GetMostFrequently(root->right, current, currentFrequency,
- maxFrequency, mostFrequently);
- }