Issue with C++ solution for Problem 16.8. (Generate binary trees)

#1

I found an issue with Problem 16.8. (Generate binary trees with n nodes) that sometimes the solution generates a binary trees with number of nodes less than n. Although the number of generated trees are correct (tested by the test engine), the actual trees are not. For example, with n = 5, the solution in the book generates a tree with preorder traversal with markers: “0 nullptr nullptr”.

The problem is at the line result.emplace_back(new BinaryTreeNode{0, move(left), move(right)}); the move() function call leaves the left and right reference nullptr.

I suggest to change to clone a the whole generated subtree rather than just move the root
result.emplace_back(new BinaryTreeNode{0, Clone(left), Clone(right)});. The Clone() function is as follows:

NodePtr Clone(const NodePtr& root) {
  if (!root) return nullptr;
  return unique_ptr<BinaryTreeNode<int>>(new BinaryTreeNode<int>{root->data, Clone(root->left), Clone(root->right)});
}
0 Likes

#2

Hey Duc,

Awesome! Much appreciated for your reporting on this issue. I have fixed this based on your suggestion.

BTW, it is sad that C++ does not support native deep copy functionality for unique_ptr. The reason is probably the design of unique_ptr does not want to support this in the very beginning.

0 Likes