From 3b3916531631ee62ba54767e42aac6e12798f93e Mon Sep 17 00:00:00 2001 From: Luke Else Date: Wed, 13 Apr 2022 21:08:58 +0100 Subject: [PATCH] Completed 'Find' function --- C#/Datastructures/BinarySearchTree/Tree.cs | 34 ++++++++++++++++++---- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/C#/Datastructures/BinarySearchTree/Tree.cs b/C#/Datastructures/BinarySearchTree/Tree.cs index 146c456..67a8bf6 100644 --- a/C#/Datastructures/BinarySearchTree/Tree.cs +++ b/C#/Datastructures/BinarySearchTree/Tree.cs @@ -8,14 +8,14 @@ namespace C_.Datastructures.BinarySearchTree public TreeNode? Root { get; set; } public int Count { get; set; } - public Tree Create(){ + public static Tree Create(){ //Create a new Tree with no Head return new Tree{ Root = null, Count = 0 }; } - public Tree Create(T? value){ + public static Tree Create(T? value){ //Create a new Tree with Head return new Tree{ Root = TreeNode.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? 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)