In modern C++ it is often recommended to use unique_ptr
when dealing with binary trees to make the ownership of subtrees explicit. For instance, Elements of Programming Interviews recommends:
template <typename T>
struct Node {
T data;
unique_ptr<Node<T>> left, right;
};
I'm just learning C++11 features, and I'm wondering what is the most convenient way to initialize a binary tree corresponding to a certain structure. My use case is to write unit tests for specific trees. For example, I want to generate this tree:
5
/ \
3 4
/ \
1 2
The following does work, but it is really cumbersome:
// first attempt: temporary variables & high syntactic noise
unique_ptr<Node<int>> tmp_n1(new Node<int>{1, nullptr, nullptr});
unique_ptr<Node<int>> tmp_n2(new Node<int>{2, nullptr, nullptr});
unique_ptr<Node<int>> tmp_n3(new Node<int>{3, move(tmp_n1), move(tmp_n2)});
unique_ptr<Node<int>> tmp_n4(new Node<int>{4, nullptr, nullptr});
unique_ptr<Node<int>> root(new Node<int>{5, move(tmp_n3), move(tmp_n4)});
What I was hoping to achieve is to get rid of the temporary variables, and initialize the tree in one nested statement. It would be nice if the code structure would resemble the tree structure. However, the following attempt fails with a "could not convert" error:
// second attempt: nested, but still a lot of syntax noise
unique_ptr<Node<int>> root(new Node<int>{5,
new unique_ptr<Node<int>>(new Node<int>{3,
new unique_ptr<Node<int>>(new Node<int>{1, nullptr, nullptr}),
new unique_ptr<Node<int>>(new Node<int>{2, nullptr, nullptr})
}),
new unique_ptr<Node<int>>(new Node<int>{4, nullptr, nullptr})
});
Any ideas how to write such tree initializations in a syntactically clean, concise, flexible way?