I need to calculate a range sum using a splay tree.
I have implemented Insert,Find,Remove and Splay methods and they are working fine, But i'm having trouble with calculating the summation of a given range in the tree.
Note: The trees in the test cases are very deep and i can't use recursive solutions.
Here's my tree class implementaion in C#:
public class Nodes
{
public Nodes LeftChild { get; set; }
public Nodes RightChild { get; set; }
public Nodes Parent { get; set; }
public int Key { get; set; }
public bool IsLeftChild => Parent != null && Parent.LeftChild.Key == Key;
public Nodes(int key = -1, Nodes left = null, Nodes right = null, Nodes parent = null)
{
this.LeftChild = left;
this.RightChild = right;
this.Parent = parent;
this.Key = key;
}
}
And here's my summation method:
public Nodes Summation(Nodes current, int low, int high)
{
if (current == null) return current;
if (low > high) return current;
Nodes temp;
temp = new Nodes(current);
sumData = new List<int>();
while (temp != null)
{
temp = Splay(temp, low);
if (temp.Key < low)
temp = temp.RightChild;
else
temp.LeftChild = null;
temp = Splay(temp, high);
if (temp.Key > high)
temp = temp.LeftChild;
else
temp.RightChild = null;
sumData.Add(temp.Key);
if (temp.LeftChild != null)
{
temp.LeftChild.Parent = temp.Parent;
temp = temp.LeftChild;
}
else
break;
}
return current;
}
The problem is in this method i need to make a copy of my original tree but i can't make a copy and it always changes the original tree so the tree will be messed up.
I would appreciate if you could help fix this method or help me implement a better one.
I have implemented the whole tree my self. Below i have posted the whole code so others can use it.
Splay tree implementation in C# using non-recursive methods:
P.S: I have modified some parts of the code for my course in university so you can ignore some parts of the code.