Binary Tree Data Structure With Examples

A Binary Tree is defined as a Tree Data Structure where each node (left and right ) has only 2 children. Since each element in a Tree can have only 2 children, we typically named them left and right child.

Binary Tree Representation

A Binary Tree is represented by the topmost Node (Commonly known as the “Root Node”). If the tree is empty then the value of root is null. Each node of a Tree contains the followings parts:

• Data
• Maximum 2 child
• Ancestors

Level Representation

Below is the Level representational graph. All the sibling child represents the level of the Tree.

Basic Operations Of Binary Tree:

• Build Tree Preorder (Creating B Tree)
• Inserting an element
• Searching in Binary Tree
• Removing an element
• Traversing the Tree

Build Binary Tree Preorder (Creating Binary Tree)

We have an array of values, using those values we have to build a Binary Tree. For this follow the following steps:

• Traverse to left until you don’t get -1 or null.
• When you got -1 or null the swift to the right side.
• If both left and right are null or -1, -1 then move to one level up.

For example : we have an array and are going to create a Tree.
[1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1]

Creating B Tree

Below is the example in Java for creating tree. By running this code if you got first element of the array (in the below case 1) then the tree is created successfully. Recursing is used to iterate over the array.

``````
public class BinaryTreeBT {

static class Node{
int data;
Node left;
Node right;

Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}

// creating binary tree
static class BinaryTree{
static int id = -1;

public static Node createBinary(int nodes[]){
id++;
if(nodes[id] == -1){
return null;
}
Node myNode = new Node(nodes[id]);
myNode.left = createBinary(nodes);
myNode.right = createBinary(nodes);
return myNode;
}

}

public static void main(String[] args) {
int nodeArr[] = {1, 2, 4,-1, -1, 5, -1, -1, 3, -1, 6, -1, -1};
BinaryTree tree = new BinaryTree();
Node result = tree.createBinary(nodeArr);
System.out.println(result.data);

}
}
``````

Result Diagram:

Representing the above array as a Tree structure.

Before learning the operations of the Tree you should learn about the Tree Traversal. B Tree Traversal means to iterate the Tree by the elements.

Operations:

1. Inserting an element into the B Tree.
2. Searching into Tree
3. Removing an element from the Tree