Binary Trees in C++. Hello readers, now we will begin our…
By: Aman Kumar Goyal
Tags: Data Structures, Computer Science, Programming, Binary Tree, Cpp

Hello readers, now we will begin our discussion of binary trees you might have seen linear data structures but a tree is a non-linear one. So, lets dive deep in the details of binary tree and see what are they? How are they implemented? and various functionalities of binary tree.

A tree is a non-linear data structure with hierarchical arrangement of data elements called nodes. The central node at the top is called root node as it is the root of tree and all elements can be accessed by this node. The top nodes are parent node and other nodes connected to it are its child, we handle trees through this parent child relationship. Two non root nodes connected to same parent are called siblings.

There are many types of trees and our discussion will remain specific to binary tree.

Binary Tree

A binary tree is a tree in which each parent node has at most two children i.e each node can have either 0,1 or 2 child nodes.

You can see in the figure above each node has at most 2 nodes. We refer to child nodes as left and right node.

Types

Based on structure of tree a binary tree can be classified into:

Complete Binary Tree

In complete binary tree, all levels are filled except possibly the last one, and all nodes are filled in as far left as possible i.e. it can be possible that nodes at right are not connected to any other node.

Full Binary Tree

In full binary tree, each node has either 0 or 2 nodes.

Perfect binary tree

In perfect binary tree, all nodes have two children and all leaves are at the same level.

Common Terminologies

Root

Root nodes is the topmost nodes of a tree.

A is root and parent of it’s child nodes B and C

Parent Node

Nodes which are connected to other nodes in the downward direction are called parent nodes as they act as parent to other subsequent nodes.

Child Node

Nodes connected to parent node are called as the child nodes of that parent.

Leaf Node

Leaf nodes are the last nodes i.e. nodes with no children or node present at last level of a branch.

Internal Node

Node which is present at position other than last level. In other words, nodes having 1 or more child nodes i.e. these are nodes other than the leaf nodes.

Depth of a node

Depth of a node is the number of edges between the node and root node.

Height of a node

Height of a node is the number of edges between the nodes and its leaf nodes. Height of root node is the height of tree.

Creating Node of Tree

Now, we have seen the basic terminologies of binary tree and we will begin understanding the implementation and working of binary tree. The basic unit of a binary tree is its node and to move ahead we first have create a node so lets see how can we create node of a binary tree.

Each node contains three components:

Pointer to left sub-tree.

Pointer to right sub-tree.

Data element

A node of binary tree having data A and pointer to left subtree and right subtree node

class node{

public:

int data;

node* left;

node* right;



node(int d){

data = d;

left=NULL;

right = NULL;

}

};

We have used class instead of structure as we are in C++, we take three variables data for storing data elements, and two pointers left and right of data type ‘node’ as data type of a pointer to node should be same as that of the node. We have used a constructor of same name as class i.e. node, in node constructor data is passed and it is stored in data block, and left and right pointers are set to NULL as default.

Tree Traversals

Traversal is accessing each node of a tree, traversal can be done in many fashions and we will discuss them one by one.

PostOrder

Post here means the parent will be accessed last, i.e. first we access left subtree then right subtree then parent node. The order would be Left → Right →Parent.

Algorithm

Until all nodes are traversed −

Step 1 − Recursively traverse left subtree.

Step 2 − Recursively traverse right subtree.

Step 3 − Visit root node.

Lets see what would be the postorder traversal of above tree.

POSTORDER: A → C → E → D → B → H → I → G → F

InOrder

Inorder here means that will be access the tree in a order which is left to right, i.e. first we access left subtree then parent node then right subtree. The order would be Left → Parent → Right .

Algorithm

Until all nodes are traversed −

Step 1 − Recursively traverse left subtree.

Step 2− Visit root node.

Step 3− Recursively traverse right subtree.

Lets see what would be the inorder traversal of above tree.

INORDER: A → B → C → D → E → F → G → H → I

PreOrder

Pre here means the parent will be accessed first, i.e. first we access the parent node the left subtree then right subtree. The order would be Parent → Left → Right .

Algorithm

Until all nodes are traversed −

Step 1− Visit root node.

Step 2− Recursively traverse left subtree.

Step 3− Recursively traverse right subtree.

Lets see what would be the preorder traversal of above tree.

PREORDER: F → B → A → D → C → E → G → I → H

LevelOrder

In levelorder traversal we will access the tree level by level from left to right . We will implement it using two functions one to traverse over a particular level and other to traverse over all levels by calling the first function.

Lets see what would be the levelorder traversal of above tree.

LEVELORDER: F → B → G → A → D → I → C → E → H

void printKLevel(node* root,int l){

if(root==NULL)

return;



if(l==1){

cout<<root->data<<" ";

return;

}

printKLevel(root->left , l-1);

printKLevel(root->right , l-1);

}

void printALLevels(node* root){

int h=height(root);



for(int i=0 ; i<h ; i++){

printKLevel(root,i);

cout<<endl;

}

return;

}

Binary Tree Operation

Building Tree

node* buidtree(string s){

if(s=="true"){

int d;

cin>>d;

node*root=new node(d); string l;

cin>>l; if(l=="true"){

root->left=buidtree(l);

}

string r;

cin>>r; if(r=="true"){

root->right=buidtree(r);

}

return root;

}

return NULL;

}

Insertion

/*function to insert element in binary tree */ void insert(Node* temp, int key){ queue<Node*> q;

q.push(temp); while (!q.empty()) {

Node* temp = q.front();

q.pop(); if (!temp->left) {

temp->left = new Node(key);

break;

} else {

q.push(temp->left); } if (!temp->right) {

temp->right = new Node(key);

break;

} else {

q.push(temp->right); }

} }

Deletion

Deletion in binary tree is simpler than other trees as there is no particular ordering, but we remove the rightmost element last level of tree as it would shrink the size of tree on deletion.

If there is no specific element is not defined then the right most part gets deleted but that’s generally not used unlike stack, so generally the user or tester determines the element to be deleted we will delete the elements in two steps:

First, we will swap the element to be deleted with the last i.e. the rightmost element of last level.

Second, we will remove the element present at rightmost position.

Height of Tree

Height of tree is the height of root node which is number of edges between the root node and last node.

We can calculate the height by calculating number of edges in the left and right subtree and then take the max of them and increment by 1, recursion makes is pretty easy. We add 1 because of the extra edge used to connect the left or right subtree with root node.

int height(node* root){

if(root==NULL)

return 0;



int ls = height(root->left);

int rs = height(root->right);

return max(ls,rs)+1;

}

The End…

Hope I have been able to explain each topic well and now its your turn to code binary tree yourself it will make your concepts more strong.

Keep learning and Happy Programming :— )