【发布时间】:2014-12-07 20:28:42
【问题描述】:
我有一棵包含数学表达式的二叉树。我使用数组将二叉树保存在内存中。 我将运算符(如 + 或 tan)保存为数组中的字符串。对于每个 i 节点,左节点索引为 2*i+1,右节点索引为 2*i+2。每个节点都可以是操作数或运算符。我想将二叉树转换为数学表达式,如字符串: "2+tan(tan(10))" 。 c#中如何将二叉树转换为数学表达式?
+
/ \
2 tan
/ \ ===> "2+tan(tan(10))"
tan
/ \ / \
10
这是我的二叉树代码:
public class Tree
{
private readonly List<Node> _nodes;
public Tree(int size)
{
_nodes = new List<Node>();
for (var i = 0; i < size; i++)
{
_nodes.Add(new Node(i, null));
}
for (var i = 0; i < size; i++)
{
if (2*i+1 > size-1 || 2*i+2 > size-1)
break;
_nodes[i].Left = _nodes[2*i + 1];
_nodes[i].Right = _nodes[2*i + 2];
}
}
...
}
【问题讨论】:
标签: c# math tree binary-tree binary-search-tree