A binary tree is a tree data structure in which every node has at most two children, which are referred to as the left child and the right child.
To implement a binary tree, let's first define the Node class, which will represent a single node in the tree. Each node can have left and right nodes, so we will have left & right pointers in the class.
class Node {
public:
int data;
Node *left;
Node *right;
};
Now we can start creating our tree:
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
Full Program :
#include
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
void print(Node *root, int space=0, int t=0) {
int COUNTER = 3;
if(root == NULL)
return;
space += COUNTER;
print(root->right, space, 1);
for(int i = COUNTER; i < space; i++) {
cout << " ";
}
if(t == 1) { // Right node
cout << "/ " << root->data << endl;
}
else if (t == 2) { // Left node
cout << "\\ " << root->data << endl;
}
else { // Root node
cout << root->data << endl;
}
print(root->left, space, 2);
}
int main() {
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
print(root);
return 0;
}
You might be interested in this too.: