Having difficulty initializing a struct
consisting of a tree node and a bool
using auto [aaa, aaa]
syntax:
Identifier 'node' is undefined
I've tried using the struct
type (NodeAndState
) as well as decltype
instead of auto
, but nothing seems to work.
The code is exactly as in "Elements of Programming Interviews".
#include <memory>
#include <algorithm>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
template <typename T>
struct BinaryTreeNode
{
T data;
unique_ptr<BinaryTreeNode<T>> left, right;
explicit BinaryTreeNode(const T& data) : data(data) {}
BinaryTreeNode(T data, unique_ptr<BinaryTreeNode<T>>&& left,
unique_ptr<BinaryTreeNode<T>>&& right) : data(data), left(move(left)),
right(move(right)) {}
};
vector<int> InorderTraversal(const unique_ptr<BinaryTreeNode<int>>& tree) {
vector<int> result;
struct NodeAndState {
const BinaryTreeNode<int>* node;
bool left_subtree_traversed;
};
stack<NodeAndState> in_process(
{{tree.get(), false}});
while (!empty(in_process)) {
// The problem is here
auto [node, left_subtree_traversed] = in_process.top();
in_process.pop();
if (node) {
if (left_subtree_traversed) {
result.emplace_back(node->data);
} else {
in_process.push({node->right.get(), false});
in_process.push({node, true});
in_process.push({node->left.get(), false});
}
}
}
return result;
}