Updated Min, Max and Find functions to use stacks
This commit is contained in:
parent
9de49129e7
commit
1c14ff75d6
@ -1,4 +1,5 @@
|
||||
using C_.Datastructures.BinaryTree;
|
||||
using C_.Datastructures.Stack;
|
||||
using System;
|
||||
|
||||
namespace C_.Datastructures.BinaryTree
|
||||
@ -47,51 +48,60 @@ namespace C_.Datastructures.BinaryTree
|
||||
return;
|
||||
}
|
||||
|
||||
public TreeNode<T>? Find(T value)
|
||||
private Stack<TreeNode<T>>? Find(T value)
|
||||
{//Return true if the item can be found within the tree
|
||||
if (Root == default || Root.Value!.Equals(default))
|
||||
return default;
|
||||
|
||||
TreeNode<T>? current = Root;
|
||||
|
||||
while (current != default)
|
||||
Stack<TreeNode<T>>? stack = Stack<TreeNode<T>>.Create(Root);
|
||||
|
||||
while (stack.Peek() != default)
|
||||
{
|
||||
//Compare value at node to see if we are looking for the root item
|
||||
if (current.Value!.Equals(value))
|
||||
return current;
|
||||
if (stack.Peek()!.Value!.Equals(value))
|
||||
return stack;
|
||||
|
||||
current = Traverse(value, current);
|
||||
stack.Push(Traverse(value, stack.Peek()));
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
public TreeNode<T>? Min(TreeNode<T>? node)
|
||||
{//Returns the Minimum node from a given subtree
|
||||
private Stack<TreeNode<T>>? Min(TreeNode<T>? node)
|
||||
{//Returns a Stack with the value on top being the minimum of the subtree
|
||||
|
||||
if(node == default)
|
||||
return default;
|
||||
|
||||
while(true){
|
||||
if (node!.Left == default)
|
||||
return node;
|
||||
//Stack to store and be able to get the parent values
|
||||
Stack<TreeNode<T>> stack = Stack<TreeNode<T>>.Create(node);
|
||||
|
||||
node = node.Left;
|
||||
while(true){
|
||||
if (stack.Peek()!.Left == default)
|
||||
return stack;
|
||||
|
||||
stack.Push(stack.Peek()!.Left);
|
||||
}
|
||||
}
|
||||
|
||||
public TreeNode<T>? Max(TreeNode<T>? node)
|
||||
{//Returns the Minimum node from a given subtree
|
||||
private Stack<TreeNode<T>>? Max(TreeNode<T>? node)
|
||||
{///Returns a Stack with the value on top being the maximum of the subtree
|
||||
if(node == default)
|
||||
return default;
|
||||
|
||||
while(true){
|
||||
if (node!.Right == default)
|
||||
return node;
|
||||
//Stack to store and be able to get the parent values
|
||||
Stack<TreeNode<T>> stack = Stack<TreeNode<T>>.Create(node);
|
||||
|
||||
node = node.Right;
|
||||
while(true){
|
||||
if (stack.Peek()!.Right == default)
|
||||
return stack;
|
||||
|
||||
stack.Push(stack.Peek()!.Right);
|
||||
}
|
||||
}
|
||||
|
||||
private TreeNode<T>? Traverse(T value, TreeNode<T> node)
|
||||
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;
|
||||
|
Loading…
Reference in New Issue
Block a user