Lycaon - 1 year ago 195
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:

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;

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