DataStructuresCSharp/C#/Datastructures/BinarySearchTree/Tree.cs

83 lines
2.2 KiB
C#

using C_.Datastructures.BinarySearchTree;
using System;
namespace C_.Datastructures.BinarySearchTree
{
internal class Tree<T> where T:IComparable
{
public TreeNode<T>? Root { get; set; }
public int Count { get; set; }
public Tree<T> Create(){
//Create a new Tree with no Head
return new Tree<T>{
Root = null,
Count = 0
};
}
public Tree<T> Create(T? value){
//Create a new Tree with Head
return new Tree<T>{
Root = TreeNode<T>.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<T>.Create(value);
return;
}
//Find position to insert
TreeNode<T> node = Root;
node = Descend(value, node)!;
if (value.CompareTo(node.Value) < 0)
{//Insert to left
node.Left = TreeNode<T>.Create(value);
return;
}
//Insert to right
node.Right = TreeNode<T>.Create(value);
return;
}
public bool Find(T value){
var x = Descend(value, Root);
return true;
}
private TreeNode<T>? Descend(T value, TreeNode<T>? 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<T>? node;
if (value.CompareTo(current.Value) < 0)
{//Descend left
node = Descend(value, current.Left);
if (node == null)
{
return current;
}
return node;
}
else
{//Descend right
node = Descend(value, current.Right);
if (node == null)
{
return current;
}
return node;
}
}
}
}