找出二叉查找树中出现频率最高的元素。树中结点满足left->val <= root->val <= right->val。如果多个元素出现次数相等,返回最小的元素。
在一个有序数组中,我们查找出现频率最高的元素,很简单,顺序扫描一遍即可统计出。那么我们对二叉查找树也可以用类似方式统计,因为中序遍历序列就是有序序列,所以我们在中序遍历的过程中就可以统计出出现频率最高的元素。
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);
}