Binary Tree DS
Binary Tree DS
A binary tree is a tree data structure in which each parent node can have at most two children.
Each node of a binary tree consists of three items:
data item
address of left child
address of right child
Binary Tree Implementation
A Binary tree is implemented with the help of pointers. The first node in the tree is represented by the root
pointer. Each node in the tree consists of three parts, i.e., data, left pointer and right pointer. To create a
binary tree, we first need to create the node. We will create the node of user-defined as shown below:
1. class Node
2. {
3. int data,
4. Node *left, *right;
5. }
The full binary tree is also known as a strict binary tree. The tree can only be considered as the full binary
tree if each node must contain either 0 or 2 children. The full binary tree can also be defined as the tree in
which each node must contain 2 children except the leaf nodes. Let's look at the simple example of the
Full Binary tree.
Complete Binary Tree
The complete binary tree is a tree in which all the nodes are completely filled except the last level. In the
last level, all the nodes must be as left as possible. In a complete binary tree, the nodes should be added
from the left. Let's create a complete binary tree.
The above tree is a complete binary tree because all the nodes are completely filled, and all the nodes in
the last level are added at the left first.
Perfect Binary Tree
A tree is a perfect binary tree if all the internal nodes have 2 children, and all the leaf nodes are at the
same level.
Let's look at a simple example of a perfect binary tree.
The below tree is not a perfect binary tree because all the leaf nodes are not at the same level.
The degenerate binary tree is a tree in which all the internal nodes have only one children. Let's
understand the Degenerate binary tree through examples.
The above tree is a degenerate binary tree because all the nodes have only one child. It is also known as a
right-skewed tree as all the nodes have a right child only.
The above tree is also a degenerate binary tree because all the nodes have only one child. It is also known
as a left-skewed tree as all the nodes have a left child only.
Balanced Binary Tree
The balanced binary tree is a tree in which both the left and right trees differ by at most 1. For
example, AVL and Red-Black trees are balanced binary tree. Let's understand the balanced binary tree
through examples.
The above tree is a balanced binary tree because the difference between the left subtree and right subtree
is zero.
The above tree is not a balanced binary tree because the difference between the left subtree and the right
subtree is greater than 1.