Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections.Generic;
- public class Node
- {
- public int Data;
- public Node Left;
- public Node Right;
- public Node(int data)
- {
- Data = data;
- Left = null;
- Right = null;
- }
- }
- public class BinarySearchTreeChecker
- {
- private const long INT_MIN_LONG = long.MinValue;
- private const long INT_MAX_LONG = long.MaxValue;
- public static bool IsBinarySearchTree(Node root)
- {
- return IsBSTUtil(root, INT_MIN_LONG, INT_MAX_LONG);
- }
- private static bool IsBSTUtil(Node node, long min_val, long max_val)
- {
- if (node == null)
- {
- return true;
- }
- if (node.Data < min_val || node.Data > max_val)
- {
- return false;
- }
- bool isLeftValid = IsBSTUtil(node.Left, min_val, (long)node.Data - 1);
- if (!isLeftValid)
- {
- return false;
- }
- bool isRightValid = IsBSTUtil(node.Right, (long)node.Data, max_val);
- return isRightValid;
- }
- }
- public class Program
- {
- public static void Main()
- {
- Console.WriteLine("--- Binary Search Tree Checker ---");
- Console.WriteLine("Enter the data for the 7 nodes separated by spaces:");
- Console.Write("Enter 7 numbers: ");
- string inputLine = Console.ReadLine();
- int[] elements;
- try
- {
- elements = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(s => int.Parse(s.Trim()))
- .ToArray();
- }
- catch (FormatException)
- {
- Console.WriteLine("\nInvalid input. Please ensure all entries are integers separated by spaces. Exiting.");
- return;
- }
- if (elements.Length != 7)
- {
- Console.WriteLine($"\nInput error: Expected 7 numbers but received {elements.Length}. Exiting.");
- return;
- }
- Node root = new Node(elements[0]);
- root.Left = new Node(elements[1]);
- root.Right = new Node(elements[2]);
- root.Left.Left = new Node(elements[3]);
- root.Left.Right = new Node(elements[4]);
- root.Right.Left = new Node(elements[5]);
- root.Right.Right = new Node(elements[6]);
- Console.WriteLine("\n--- Tree Construction Complete. Checking structure... ---");
- bool is_bst = BinarySearchTreeChecker.IsBinarySearchTree(root);
- Console.Write("\nThe inputted data elements are structured as a: ");
- if (is_bst)
- {
- Console.WriteLine("BINARY SEARCH TREE (BST).");
- }
- else
- {
- Console.WriteLine("NOT a Binary Search Tree (BST).");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment