0

我需要一个函数来返回从表达式 AB*B+ 构建的树。每个节点的类型struct

struct Node {
std::string name;
Node* left;
Node* right;
}

我现在需要解析表达式 AB*B+。我有一叠std::vector<Node*>

1)为A创建节点,将其推入堆栈

2)为B创建节点,将其推入堆栈

3)为*创建节点,弹出B,赋值给右边,弹出A,赋值给左边。将 * 压入堆栈

这一直持续到表达式完成。

现在,如果我可以访问树的根,我应该能够访问每个节点。但是,由于我将它们全部分配在函数的堆栈上,我猜测当我返回根节点时,虽然该节点可能被复制到 RHS,但它指向的子节点是无效的。

我是否应该在创建节点时将所有节点存储在不同std::vector<Node> nodes的位置。使用栈创建父子关系,然后nodes按值返回?这行得通吗?

或者我应该用std::shared_ptr这个来代替?如果是这样,你能举例说明如何做吗?

4

1 回答 1

0

By copy, I am guessing you mean this :

    Node* root = Null;
    root = nodeStack.pop();

I you really are following your algorithm perfectly , and you mean copy as the above. It should work. Definitely. May be there is something wrong with the algorithm implementation.

于 2013-07-03T06:37:09.217 回答