将平面线性树表示转换为记忆树表示

transform flat linear tree representation into memory tree representation

我有这样的字符串:

*b+a-aQa

并希望将其转换为这样的分层树结构:

树将由这样的节点组成:

public class TreeNode : ITreeNode
{
    public string Expression { get; set; }
    public bool Terminal { get; set; }
        public List<ITreeNode> Children { get; set; }
}

public interface ITreeNode
{
    string Expression { get; set; }
    bool Terminal { get; set; }
    List<ITreeNode> Children { get; set; }
}

这里的表达式是,例如:

*

Terminal 表示节点是否为终端节点 (b, a, a, a)。

我正在尝试想出一种算法来创建给定字符串的树。任何帮助将不胜感激。谢谢!

为了提供更多上下文,这与此相关paper

PS:

另一个例子:

Q*+-abcd

其含义如下(Q=平方根):

有点像二叉堆,但又不完全是。添加节点时,您知道结构(0、1 或 2 个子节点),但您只是在很久以后才读取子节点的内容。

您可以使用队列而不是堆栈来管理它

private static Node Parse(TextReader reader)
{            
    var nodes = new Queue<Node>();

    var root = new Node();
    nodes.Enqueue(root);   

    int ch;

    while ((ch = reader.Read()) != -1)
    {
        char token = (char)ch;

        // syntax check 1: the queue should not be empty
        var node = nodes.Dequeue();  
        node.Symbol = token;

        if ("Q".IndexOf(token) >= 0)
        {
            node.Left = new Node();
            nodes.Enqueue(node.Left);
        }
        else if ("+-*".IndexOf(token) >= 0)
        {
            node.Left = new Node();
            nodes.Enqueue(node.Left);
            node.Right = new Node();
            nodes.Enqueue(node.Right);
        }
        // else : 0 children
    }

    // syntax check 2: the queue should now be empty
    return root;         
}

你可以这样称呼它

var tree = Parse(new StringReader("Q*+-abcd"));