void postOrder(Node *root) {
Node* lastPrinted = nullptr;
stack<Node*> container;
container.push(root);
while (!container.empty()) {
Node* current = container.top();
function<void()> printer = [&](){
cout << current->data << " ";
lastPrinted = current;
container.pop();
};
if (!current->right & !current->left) {
printer();
continue;
}
if (current->right) {
if (current->right==lastPrinted) {
printer();
continue;
}
else container.push(current->right);
}
if (current->left) {
if (current->left==lastPrinted) {
printer();
continue;
}
else container.push(current->left);
}
}
}
上面的代码有效。在lambda函数中,未指定可变打印机。但是在函数中,container和lastPrinted被修改。为什么允许?
这里是Node类,以备您测试:
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};