给定一个二叉搜索树,其中可能包含重复项,但 BST 的所有其他逻辑都是完整的,确定最常出现的元素。
class TreeNode
{
public:
TreeNode* right = NULL;
TreeNode* left = NULL;
int val;
TreeNode(int value)
{
val = value;
}
};
// To keep track of the frequency of the value/node
struct holder
{
public:
TreeNode* most = NULL;
int count = 0;
};
int frequencyOfNode(TreeNode* root, struct holder* ptr)
{
if (root == NULL)
{
return 0;
}
int left = frequencyOfNode(root->left, ptr);
int right = frequencyOfNode(root->right, ptr);
// need to check of left and right are nor null
if (left != 0 && root->val == root->left->val)
{
return 1 + left;
}
else if (right != 0 && root->val == root->right->val)
{
return 1 + right;
}
else
{
// left has a higher frequency
if (left >= right)
{
// left is bigger;
if (left > ptr->count)
{
ptr->most = root->left;
ptr->count = left;
}
}
else
{
// right has a higher frequency
if (right > ptr->count)
{
ptr->most = root->right;
ptr->count = right;
}
}
return 1;
}
}
我正在对二叉搜索树进行后序遍历。当节点以连续顺序出现时,我的逻辑有效,但如果节点不是连续顺序;节点的频率被重置。
我的时间是 O(n),空间是 O(1)。
问题是节点没有连续链接。
我的示例树:
int main()
{
TreeNode *root = new TreeNode(6);
root->right = new TreeNode(8);
root->right->left = new TreeNode(7);
root->right->right = new TreeNode(8);
root->right->right->right = new TreeNode(8);
root->right->right->right->right = new TreeNode(9);
root->right->right->right->right->left = new TreeNode(8);
root->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->left->right->right = new TreeNode(5);
root->left->right->right->right = new TreeNode(5);
root->left->left = new TreeNode(1);
root->left->left->right = new TreeNode(1);
root->left->left->right->right = new TreeNode(1);
root->left->left->right->right = new TreeNode(2);
root->left->left->left = new TreeNode(0);
struct holder freq;
int ran = frequencyOfNode(root, &freq);
std::cout << "random" << ran << std::endl;
std::cout << "The Node: " << freq.most->val << " frequency " << freq.count
<< std::endl;
return 0;
}
当节点不连续(即8-> 8-> 8-> 9-> 8)时,我真的很困惑如何考虑。