Binary Tree Representation in C++

A Binary Tree in C++ is represented as pointers connecting to each other in a hierarchical manner where a node can have two further pointers namely, a right child and a left child. The pointers point to the value of the next pointing node.

Let’s understand through an illustration how we can represent a tree as pointers in C++:

If there is no left or right child of a particular node, the respective pointer will by default point to NULL.

In C++ language, we represent a tree by creating a Structure “Node” and then defining data for the node and left and right pointers for that node, hence initializing them. In the main function, we can directly allocate memory dynamically using “new” keyword and assign further values to nodes as depicted below.

Representation of a Tree through Pseudocode (Creating a Binary Tree):

Struct Node{

// Defining value of the node.
int data;

// Left reference ptr to the node.
Struct Node* left;

// Right reference ptr to the node.
Struct Node* right;

// Method to initialize the above values.
Node (int val)
{
  data = val;
  left = right = NULL; 
}

};

main()
{
   // Creating a new node by using dynamic allocation.
   Struct Node* root = new Node(1);
   root -> left = new Node(2);
   root -> right = new Node(3);
   root -> left -> right = new Node(5);

}

The tree created above would look something like this when drawn:

Special thanks to Priyanshi Goel for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article