Created 'Add' function for Binary Search Tree

This commit is contained in:
Luke Else 2022-04-05 22:35:33 +01:00
parent e1a85f7b53
commit e9df1cab67
2 changed files with 70 additions and 3 deletions

View File

@ -5,21 +5,74 @@ namespace C_.Datastructures.BinarySearchTree
{ {
internal class Tree<T> where T:IComparable internal class Tree<T> where T:IComparable
{ {
public TreeNode<T>? Head { get; set; } public TreeNode<T>? Root { get; set; }
public int Count { get; set; } public int Count { get; set; }
public Tree<T> Create(){ public Tree<T> Create(){
//Create a new Tree with no Head //Create a new Tree with no Head
return new Tree<T>{ return new Tree<T>{
Head = null, Root = null,
Count = 0 Count = 0
}; };
} }
public Tree<T> Create(T? value){ public Tree<T> Create(T? value){
//Create a new Tree with Head //Create a new Tree with Head
return new Tree<T>{ return new Tree<T>{
Head = TreeNode<T>.Create(value) 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;
}
private TreeNode<T>? Descend(T value, TreeNode<T>? current)
{//Keep trying to determine whether to go left or right until null node is found
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;
}
}
} }
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using C_.Datastructures.BinarySearchTree;
// See https://aka.ms/new-console-template for more information // See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!"); Console.WriteLine("Hello, World!");
@ -98,6 +99,19 @@ Console.WriteLine("Hello, World!");
//queue.Pop(); //queue.Pop();
//queue.Pop(); //queue.Pop();
Tree<int> tree = new Tree<int>();
tree.Add(4);
tree.Add(5);
tree.Add(7);
tree.Add(6);
tree.Add(2);
tree.Add(3);
tree.Add(1);
tree.Add(4);
tree.Add(7);
Console.ReadLine(); Console.ReadLine();