+Delete, if node has 2 children, subtrees

don't carry
This commit is contained in:
lukejelse04 2021-07-06 22:50:20 +01:00
parent 72ec29eafc
commit 7e538acf55
3 changed files with 103 additions and 6 deletions

View File

@ -14,6 +14,9 @@ namespace BinaryTree
tree.Add(3); tree.Add(3);
tree.Add(1); tree.Add(1);
tree.Add(4); tree.Add(4);
tree.Add(0.5);
tree.Delete(1);
} }
} }

View File

@ -20,11 +20,18 @@ namespace BinaryTree
} }
public node GetParent(){
return Parent;
}
public void SetParent(node _Parent){
Parent = _Parent;
}
public node GetLeft(){ public node GetLeft(){
return Left; return Left;
} }
public void SetLeft(dynamic _Data, node _Parent){ public void SetLeft(node _Left){
Left = new node(_Data, _Parent); Left = _Left;
} }
@ -32,8 +39,8 @@ namespace BinaryTree
public node GetRight(){ public node GetRight(){
return Right; return Right;
} }
public void SetRight(dynamic _Data, node _Parent){ public void SetRight(node _Right){
Right = new node(_Data, _Parent); Right = _Right;
} }

View File

@ -35,9 +35,9 @@ namespace BinaryTree
//Check whether we need to add the node to the left or right of //Check whether we need to add the node to the left or right of
if (_Data < Current.Data) if (_Data < Current.Data)
{ {
Current.SetLeft(_Data, Current); Current.SetLeft(new node(_Data, Current));
}else{ }else{
Current.SetRight(_Data, Current); Current.SetRight(new node(_Data, Current));
} }
@ -52,6 +52,93 @@ namespace BinaryTree
return _Current.GetRight(); return _Current.GetRight();
} }
public bool Delete(dynamic _Data){
//Traverse to the node we are trying to delete
Current = Root;
//try statement will run unless the node does not exitst, in which case it will throw an exception and return false.
try
{
while(true){
if (_Data != Current.Data)
{
Current = Traverse(_Data, Current);
}else{
break;
}
}
}
catch (System.Exception)
{
//If it can't be found, return false
return false;
}
if (Current.GetLeft() != null && Current.GetRight() != null)
{
//If it has 2 children
node temp = new node();
temp = Current.GetLeft();
while(true){
if (temp.GetRight() != null)
{
temp = temp.GetRight();
}else{
break;
}
}
Current.Data = temp.Data;
if (temp.GetLeft() != null)
{
temp.GetParent().SetRight(temp.GetLeft());
}else{
temp.GetParent().SetRight(null);
}
return true;
}else if(Current.GetLeft() != null)
{
//If it has a left child
Current.Data = Current.GetLeft().Data;
Current.SetLeft(null);
return true;
}else if(Current.GetRight() != null){
//If it has a right child
Current.Data = Current.GetRight().Data;
Current.SetRight(null);
return true;
}else{
//If it has no children
if (Current.Data < Current.GetParent().Data)
{
Current.GetParent().SetLeft(null);
return true;
}else{
Current.GetParent().SetRight(null);
return true;
}
}
}
} }
} }