Lycaon Lycaon - 3 months ago 42
C# Question

Binary Search Tree Validation

Thank you for reading my topic. I am practising a little bit with C# at Test Dome. The exercise I am currently trying to program is the following:
http://www.testdome.com/Questions/Csharp/BinarySearchTree/484?testId=21&testDifficulty=Hard

My current result:


  • Example case: Correct answer

  • Simple cases: Correct answer

  • Regular cases: Wrong answer

  • Edge cases: Wrong answer

  • Performance test: Wrong answer



You can read the code I wrote so far below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Node
{
public int Value { get; set; } // Value of {node} == integer (1,2,3,4,5)
public Node Left { get; set; } // Reference to left node (n1, n2, n3) == Node.
public Node Right { get; set; } // Reference to right node (n1, n2, n3) == Node.
public Node(int value, Node left, Node right)
{
Value = value; // (int)
Left = left; // (node)
Right = right; // (node)
}
}

public class BinarySearchTree
{
public static bool IsValidBST(Node root)
{
if (root.Left == null && root.Right == null)
return true;

else if (root.Left == null)
{
// Checking root.Right.Value
if (root.Value <= root.Right.Value)
return true;

else
return false;
}
else if (root.Right == null)
{
// Checking root.Left.Value
if (root.Value > root.Left.Value)
return true;
else
return false;
}
else
{
// Checking both Values
if (root.Value > root.Left.Value && root.Value <= root.Right.Value)
return true;
else
return false;
}
}


public static void Main(string[] args)
{
Node n1 = new Node(1, null, null);
Node n3 = new Node(3, null, null);
Node n2 = new Node(2, n1, n3);

// Execute function and write it to the console
Console.WriteLine(IsValidBST(n2));
Console.ReadLine();
}
}


I have no idea what to implement to pass the test. I don't want you to give me written-code, but more information about the exercice. Keep in mind that my current-code is far from neat. Thank you all.

Answer

You should check those other nodes root.Left and root.Right by calling IsValidBST on them if they are not null and then checking these results. Right now you only test the root node instead of descending into the tree

Comments