我使用BST的主要原因是要获得多数元素,即Value> Array.Length / 2。
因此,如果我们有一个由5个元素组成的数组,那么至少必须有至少3个元素才能被视为多数元素。
现在,我现在面临的问题是为数组中的第一个元素选择了多数元素。
这是下面的代码:
public Node nnde(Node root)
{
if (root== null)
{
root= newNode;
size++;
return root;
}
if (elm < root.elm)
{
if (root.lft != null)
{
InsertNewNode(root.lft, elm);
}
else
{
root.lft = new Node(elm);
}
}
else if (elm> root.rght)
{
if (root.rght != null)
{
InsertNewNode( root.rght, elm);
}
else
{
root.rght = new Node(elm);
}
}
return root;
}
数组中的元素:2 0 1 2 1
应该没有多数元素,但是,我当前编程的BST将其显示为2。
经过一段时间尝试弄清楚问题可能出在哪里之后,我才意识到我忘了在InsertNewNode()方法中插入简单的size ++。
编辑的代码如下:
if (elm < root.lft)
{
if (root.lft != null)
{
root.lft = InsertNewNode(root.lft, elm);
}
else
{
root.lft = new Node(elm);
size++;
}
}
else if (elm > root.rght)
{
if (root.rght != null)
{
root.rght = InsertNewNode(root.rght, elm);
}
else
{
root.rght = new Node(elm);
size++;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句