the root is passed to the Print function, whose left and right values are Null. but the thing is, if you start looking through the debugger from the line for (size_t i = 0; i < tree.GetTreeDepth(); ++i)
then you can see that the root has nodes. but when passed to the Print function, the nodes disappear again and only the value at the root remains.
i’m probably doing something wrong. what is basically wrong with my binary tree implementation?
template <typename Type>
struct Node {
Node() = default;
Node(const Type& val, Node<Type>* new_lhs = nullptr, Node<Type>* new_rhs = nullptr)
: value(val)
, lhs(new_lhs)
, rhs(new_rhs) {
}
Type value;
Node<Type>* lhs; // left-hand side
Node<Type>* rhs; // right-hand side
};
template <typename Type>
struct BinaryTree {
private:
Node<Type>* root_;
Type tree_depth_;
public:
BinaryTree()
: root_()
, tree_depth_(Type())
{}
Node<Type>* SetRoot(Node<Type>* root) {
root_ = root;
return root_;
}
Node<Type>* GetRoot() {
return root_;
}
Node<Type>* Push(Node<Type>* root, Type new_value) {
if (root == nullptr) {
return new Node<Type>(new_value);
}
else if (new_value < root->value) {
root->lhs = Push(root->lhs, new_value);
}
else if (new_value > root->value) {
root->rhs = Push(root->rhs, new_value);
}
return root;
}
void SetTreeDepth() {
std::cout << "Specify the depth of the tree: "s;
do {
std::string tmp;
std::getline(std::cin, tmp);
if (isIntNum(tmp, '0', '9') and std::stoi(tmp) > 0) {
tree_depth_ = std::stoi(tmp);
return;
}
else {
ERROR_HINT("A natural number is expected.");
}
} while (true);
}
Type GetTreeDepth() const {
return tree_depth_;
}
void Print(Node<Type>* root) {
if (root == nullptr) {
return;
}
Print(root->lhs);
std::cout << root->value << "t";
Print(root->rhs);
}
};
int main() {
setlocale(LC_ALL, "RUS");
BinaryTree<int> tree;
tree.SetTreeDepth();
for (size_t i = 0; i < tree.GetTreeDepth(); ++i) {
tree.SetRoot(tree.Push(tree.GetRoot(), GetRandomNum(0, 99)));
}
tree.Print(tree.GetRoot());
return 0;
}
in the Print function, root has only the value of the root of the tree, and the left and right descendants are Null for some reason.
void Print(Node<Type>* root) {
if (root == nullptr) {
return;
}
Print(root->lhs);
std::cout << root->value << "t";
Print(root->rhs);
}