Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- 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
- {
- private static int GetNodeData(string nodeName)
- {
- int data;
- bool isValid;
- do
- {
- Console.Write($"Enter data for {nodeName}: ");
- string input = Console.ReadLine();
- isValid = int.TryParse(input, out data);
- if (!isValid)
- {
- Console.WriteLine("Invalid input. Please enter an integer.");
- }
- } while (!isValid);
- return data;
- }
- public static void Main()
- {
- Console.WriteLine("--- Binary Search Tree Checker ---");
- Console.WriteLine("Please input the data for each position in the tree structure (7 nodes total).");
- Console.WriteLine("Your input will define the tree's structure for the check.\n");
- Node root = new Node(GetNodeData("root"));
- root.Left = new Node(GetNodeData("root.Left"));
- root.Right = new Node(GetNodeData("root.Right"));
- root.Left.Left = new Node(GetNodeData("root.Left.Left"));
- root.Left.Right = new Node(GetNodeData("root.Left.Right"));
- root.Right.Left = new Node(GetNodeData("root.Right.Left"));
- root.Right.Right = new Node(GetNodeData("root.Right.Right"));
- 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