using C_.Datastructures.BinarySearchTree; using System; namespace C_.Datastructures.BinarySearchTree { internal class Tree where T:IComparable { public TreeNode? Root { get; set; } public int Count { get; set; } public static Tree Create(){ //Create a new Tree with no Head return new Tree{ Root = null, Count = 0 }; } public static Tree Create(T value){ //Create a new Tree with Head return new Tree{ Root = TreeNode.Create(value) }; } public void Add(T value) {//Add item to the correct position in the tree (Input cannot be null) Count++; if (Root == default) {//If new node should become the root Root = TreeNode.Create(value); return; } //Find position to insert TreeNode node = Root; node = Descend(value, node)!; if (value.CompareTo(node.Value) < 0) {//Insert to left node.Left = TreeNode.Create(value); return; } //Insert to right node.Right = TreeNode.Create(value); return; } public bool Find(T value) {//Return true if the item can be found within the tree if (Root == default || Root.Value!.Equals(default)) return false; TreeNode? current = Root; while (current != default) { //Compare value at node to see if we are looking for the root item if (current.Value!.Equals(value)) return true; current = Traverse(value, current); } return false; } private TreeNode? Traverse(T value, TreeNode node) {//T is comparable so use methods to determine which way to traverse if(node == default) return default; if (value.CompareTo(node.Value) < 0) {//Traverse Left return node.Left; } //Traverse Right return node.Right; } private TreeNode? Descend(T value, TreeNode? current) {//Keep trying to determine whether to go left or right until null node is found that can be appended to if (current == default) return default; TreeNode? node; node = Descend(value, Traverse(value, current)); if (node == null) { return current; } return node; } } }