如何查找二叉搜索树中重复元素的数量
public void duplicate()
{
int repeatation = 0;
Node current = root;
Node duplicate = root;
while (current == null)
{
if (duplicate == current || duplicate == current.right || duplicate== current.left)
{
Console.WriteLine("node is repeated :" + duplicate);
repeatation++;
}
}
Console.WriteLine("number of repeatation is :" + repeatation);
}
这段代码用于二叉搜索树中的重复元素,以及一个元素重复了多少次,但它无法正常工作,你能告诉我这段代码有什么问题吗,我不确定我的代码是否正确......
public void duplicate()
{
int repeatation = 0;
Node current = root;
Node duplicate = root;
while (current == null)
{
if (duplicate == current || duplicate == current.right || duplicate== current.left)
{
Console.WriteLine("node is repeated :" + duplicate);
repeatation++;
}
}
Console.WriteLine("number of repeatation is :" + repeatation);
}
this code is for duplicate elements in binary search tree and how many time a element repeat but its not working properly ,would you tell me whats wrong with this code and i am not sure i code it right or not......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你遍历树 InOrder 你会得到重复的元素在一起,所以你只需要检查一个值何时等于前一个值,以及这种情况发生了多少次。
If you traverse the tree InOrder you'll get the repeated elements together, so you just need to check when a value equals the previous, and how many times this happens.
以下方法可能会帮助您解决此问题:
1)获取 BST 中的最大值(向右,向右,...,向右,直到到达叶子)
2)遵循以下伪代码:
Here's an approach that might help you with this issue:
1) Get the maximum value in your BST (just go right, right, ..., right until you reach a leaf)
2) follow this pseudo code:
您只需遍历 BST 一次,将每个元素保存在哈希映射中,并记录您遇到该元素的次数。
之后,迭代哈希映射并输出计数器大于 1 的每个元素。
时间复杂度:O(n)
You can just traverse your BST once saving every element in a hash-map along with a counter of how many times you have encountered that element.
After that, iterate through your hash-map and output every element that has a counter greater than 1.
Time complexity: O(n)