diff --git a/C#/Datastructures/BinarySearchTree/Tree.cs b/C#/Datastructures/BinarySearchTree/Tree.cs index 98eadfe..8fadc48 100644 --- a/C#/Datastructures/BinarySearchTree/Tree.cs +++ b/C#/Datastructures/BinarySearchTree/Tree.cs @@ -5,21 +5,74 @@ namespace C_.Datastructures.BinarySearchTree { internal class Tree where T:IComparable { - public TreeNode? Head { get; set; } + public TreeNode? Root { get; set; } public int Count { get; set; } public Tree Create(){ //Create a new Tree with no Head return new Tree{ - Head = null, + Root = null, Count = 0 }; } public Tree Create(T? value){ //Create a new Tree with Head return new Tree{ - Head = TreeNode.Create(value) + 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; + + + } + + private TreeNode? Descend(T value, TreeNode? current) + {//Keep trying to determine whether to go left or right until null node is found + if (current == default) + return default; + + TreeNode? 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; + } + } } } \ No newline at end of file diff --git a/C#/Program.cs b/C#/Program.cs index c924e7a..1aa0b1d 100644 --- a/C#/Program.cs +++ b/C#/Program.cs @@ -1,4 +1,5 @@ using System; +using C_.Datastructures.BinarySearchTree; // See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!"); @@ -98,6 +99,19 @@ Console.WriteLine("Hello, World!"); //queue.Pop(); //queue.Pop(); +Tree tree = new Tree(); + +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();