Binary Tree
Implementation of Binary Tree
Explanation
Here, we first create a structure Node, in that the 3 data members are value, left, right and one parameterized constructor that assigns value to Node whenever new Node is created. Then we define a class in which we will declare all functions related to the binary tree for now it has only constructors and a variable storing address to root Node.
Code
#include
using namespace std;
struct Node
{
int value;
Node * left;
Node * right;
Node(int val)
{
value = val;
left = NULL;
right = NULL;
}
};
class BinaryTree
{
public:
struct Node* root;
BinaryTree(int data)
{
root = new Node(data);
}
BinaryTree()
{
root = NULL;
}
};
int main()
{
BinaryTree *tree = new BinaryTree(4);
tree->root->left = new Node(2);
tree->root->right = new Node(6);
tree->root->left->left = new Node(1);
tree->root->left->right = new Node(3);
tree->root->right->left = new Node(5);
tree->root->right->right = new Node(7);
return 0;
}