Completed 'Find' function

This commit is contained in:
Luke Else 2022-04-13 21:08:58 +01:00
parent 3f97e4b770
commit 3b39165316

View File

@ -8,14 +8,14 @@ namespace C_.Datastructures.BinarySearchTree
public TreeNode<T>? Root { get; set; }
public int Count { get; set; }
public Tree<T> Create(){
public static Tree<T> Create(){
//Create a new Tree with no Head
return new Tree<T>{
Root = null,
Count = 0
};
}
public Tree<T> Create(T? value){
public static Tree<T> Create(T? value){
//Create a new Tree with Head
return new Tree<T>{
Root = TreeNode<T>.Create(value)
@ -46,14 +46,38 @@ namespace C_.Datastructures.BinarySearchTree
return;
}
public bool Find(T? value){
if (Root == default)
{
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<T>? 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<T>? Traverse(T value, TreeNode<T> 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<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)