Dev
Dev

Reputation: 3

BST Search method not returning expected result

I have been working on a BST search method which returns a boolean value indicating whether the value being searched on exists within the tree or not, whats wrong in this code? However, after returning true, control goes again to the: else if block.Can anyone tell me what I am doing wrong?

Help will be highly appreciated.Thanks in advance!!

public class Node
{

    public int Value { get; set; }

    public Node Left { get; set; }

    public Node Right { get; set; }

    public Node(int value, Node left, Node right)
    {
        Value = value;
        Left = left;
        Right = right;
    }
}

public class BinarySearchTree
{        
    public static bool Search(Node root, int value)
    {

        if (root!=null)
        {
            if (root.Value == value)
            {                    
                return true;
            }
            else if (root.Value < value)
            {
                Search(root.Right, value);
            }
            else
            {
                Search(root.Left, value);
            }

        }            
        return false;            
    }

    public static void Main(string[] args)
    {
        Node n1 = new Node(1, null, null);
        Node n3 = new Node(4, null, null);
        Node n2 = new Node(2, n1, n3);
        bool flag = Search(n2, 4);
        //flag should be true  
        Console.WriteLine("************* " + flag);
        Console.ReadKey();
    }
}

Upvotes: 0

Views: 44

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

you'll need to return the result from each invocation of the method. Currently, when control goes inside the else/if or else block you're ignoring the result returned from the method.

Also, you don't need the boolean flag just use the condition if (root != null).

public static bool Search(Node root, int value)
{
       if (root != null)
       {
           if (root.Value == value)
               return true;
           else if (root.Value < value)
               return Search(root.Right, value);
           else
               return Search(root.Left, value);
       }
       return false;
}

Upvotes: 1

Related Questions