using System;
class Node {
public int val;
public Node left, right;
public Node(int v) { val = v; left = right = null; }
}
class BST {
public Node root;
public BST() { root = null; }
public void Insert(int val) {
root = InsertRec(root, val);
}
private Node InsertRec(Node node, int val) {
if (node == null) return new Node(val);
if (val < node.val) node.left = InsertRec(node.left, val);
else node.right = InsertRec(node.right, val);
return node;
}
public bool Search(int val) {
return SearchRec(root, val);
}
private bool SearchRec(Node node, int val) {
if (node == null) return false; // reached leaf, not found
if (val == node.val) return true; // found value
if (val < node.val) return SearchRec(node.left, val); // go left
else return SearchRec(node.right, val); // go right
}
public void PrintInOrder() {
PrintInOrderRec(root);
Console.WriteLine("null");
}
private void PrintInOrderRec(Node node) {
if (node == null) return;
PrintInOrderRec(node.left);
Console.Write(node.val + " -> ");
PrintInOrderRec(node.right);
}
}
class Program {
static void Main() {
BST tree = new BST();
int[] values = {5, 3, 7, 2, 4, 8};
foreach (int v in values) tree.Insert(v);
tree.PrintInOrder();
int searchVal = 4;
bool found = tree.Search(searchVal);
Console.WriteLine(found ? $"Found {searchVal}" : $"{searchVal} not found");
}
}if (node == null) return false; // reached leaf, not found
stop search if reached empty spot
if (val == node.val) return true; // found value
found the value, return true
if (val < node.val) return SearchRec(node.left, val); // go left
go left subtree if value is smaller
else return SearchRec(node.right, val); // go right
go right subtree if value is bigger
2 -> 3 -> 4 -> 5 -> 7 -> 8 -> null
Found 4