I'm trying to implement a Binary tree (is not important if it's general binary tree, or binary search tree) and I'm having some troubles with the function that creates a node and link it into the tree.
This is the code I've written so far:
class BinaryTree {
class Node {
char data;
Node* leftChild;
Node* rightChild;
Node(char d, Node* lc, Node* rc):
data(d), leftChild(lc), rightChild(rc) {}
} *head;
int treeSize;
public:
BinaryTree(): head(0), treeSize(0) {}
// totally wrong code
void createNode(char dat) {
if (head->data < dat)
head->leftChild = new Node(dat, 0, 0);
if (head->rightChild == 0)
head->rightChild = new Node(dat, 0, 0);
if (head == 0) {
head = new Node(dat, head, head);
}
}
};
Well, I thought to implement the binary tree using a linked list, but in this case the problem will be that the head pointer will point to one of the last added node, not to the root. Another issue using linked list in this way could be to find an empty child of a node where to add a new node.
There's someone that could help me and maybe suggest a better way to implement the Binary tree?
Note: I planned to make this class a template, char is just for try it on the fly.
std::unique_ptr<Node>to hold yourNodes and in function parameters that represent ownership transfer, and liberally usestd::movewhen you want to transfer ownership, andresetwhen you assign it anew Node.