5

The main reason I'm using the BST is to get the Majority Element, being the Value > Array.Length / 2.

So, if we have an array of 5 elements, there must be a minimum of at least 3 to be considered the majority.

Now the problem I am facing at the moment is that the Majority Element is being chosen for whichever element is first in the Array.

This is the code below:

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;
}

Elements in the array: 2 0 1 2 1

There should be no majority element, however, the BST I currently programmed is showing it as 2.

user7943
  • 803
  • 7
  • 20

1 Answers1

2

After some time trying to figure out what the problem could actually be, the realization that I had forgotten to insert a simple size++ in the InsertNewNode() method came to me.

Code edited is as follows:

        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++;
            }
        }
user7943
  • 803
  • 7
  • 20