Skip to content

Commit

Permalink
Make DeepCopy iterative
Browse files Browse the repository at this point in the history
  • Loading branch information
johnthcall committed Oct 6, 2021
1 parent a4a240a commit 4c53f23
Showing 1 changed file with 29 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public SortedSet(IEnumerable<T> collection, IComparer<T>? comparer)
{
Debug.Assert(sortedSet.root != null);
this.count = sortedSet.count;
root = sortedSet.root.DeepClone();
root = sortedSet.root.DeepClone(this.count);
}
return;
}
Expand Down Expand Up @@ -1676,13 +1676,36 @@ public Node(T item, NodeColor color)

public void ColorRed() => Color = NodeColor.Red;

public Node DeepClone()
public Node DeepClone(int count)
{
Node newNode = ShallowClone();
newNode.Left = Left?.DeepClone();
newNode.Right = Right?.DeepClone();
#if DEBUG
Debug.Assert(count == GetCount());
#endif
Node newRoot = ShallowClone();

var pendingNodes = new Stack<(Node source, Node target)>(2 * Log2(count) + 2);
pendingNodes.Push((this, newRoot));

while (pendingNodes.TryPop(out var next))
{
Node clonedNode;

if (next.source.Left is Node left)
{
clonedNode = left.ShallowClone();
next.target.Left = clonedNode;
pendingNodes.Push((left, clonedNode));
}

if (next.source.Right is Node right)
{
clonedNode = right.ShallowClone();
next.target.Right = clonedNode;
pendingNodes.Push((right, clonedNode));
}
}

return newNode;
return newRoot;
}

/// <summary>
Expand Down

0 comments on commit 4c53f23

Please sign in to comment.