Assuming your FactorTreeNodeclass
is something like this:
class FactorTreeNode
{
public FactorTreeNode(long key) { this.Key = key; }
public FactorTreeNode Left { get; set; }
public FactorTreeNode Right { get; set; }
public long Key { get; private set; }
}
Then this will work:
private void LabelDisplayCondensed(FactorTreeNode root)
{
string result = Convert.ToString(root.Key) + " =";
long prevFactor = 0;
int exponent = 0;
bool firstFactor = true;
FactorTreeNode currentNode = root;
while (currentNode != null)
{
long nextFactor = currentNode.Left == null ?
currentNode.Key :
currentNode.Left.Key;
if (nextFactor != prevFactor && prevFactor != 0)
{
result += WriteFactor(prevFactor, exponent, ref firstFactor);
exponent = 1;
}
else
{
exponent++;
}
prevFactor = nextFactor;
currentNode = currentNode.Right;
}
result += WriteFactor(prevFactor, exponent, ref firstFactor);
MessageBox.Show(result);
}
private string WriteFactor(long factor, int exponent, ref bool firstFactor)
{
string result = firstFactor ? " " : " X ";
firstFactor = false;
if (exponent == 1)
{
result += factor.ToString();
}
else
{
result += factor.ToString() + " ^ " + exponent.ToString();
}
return result;
}
Obviously this includes no checks that the tree is valid.
You probably also want to use StringBuilder
to actually build the string rather than doing all those appends.