What is Binary Tree in Data Structures ?

  • Binary tree is a special type of data structure. In binary tree, every node can have a maximum of 2 children, which are known as Left child and Right Child.
  • It is a method of placing and locating the records in a database, especially when all the data is known to be in random access memory (RAM).
  • binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as fast as in linked list.
What is Binary Tree in Data Structures

Representation of Binary Tree using Array

  • Binary tree using array represents a node which is numbered sequentially level by level from left to right. Even empty nodes are numbered.

Sample Code

// JAVA implementation of tree using array 
// numbering starting from 0 to n-1.
import java.util.*;
import java.lang.*;
import java.io.*;

class bTree {
public static void main(String[] args) {
btree_Array obj = new btree_Array();
obj.Root("P");
// obj.set_Left("Q", 0);
obj.set_Right("R", 0);
obj.set_Left("S", 1);
obj.set_Right("T", 1);
obj.set_Left("U", 2);
obj.print_Tree();
}
}

class btree_Array {
static int root = 0;
static String[] s = new String[10];

/*create root*/
public void Root(String key) {
s[0] = key;
}

/*create left son of root*/
public void set_Left(String key, int root) {
int t = (root * 2) + 1;

if (s[root] == null) {
System.out.printf("Can't set child at %d, no parent found\n", t);
} else {
s[t] = key;
}
}

/*create right son of root*/
public void set_Right(String key, int root) {
int t = (root * 2) + 2;

if (s[root] == null) {
System.out.printf("Can't set child at %d, no parent found\n", t);
} else {
s[t] = key;
}
}

public void print_Tree() {
for (int i = 0; i < 10; i++) {
if (s[i] != null)
System.out.print(s[i]);
else
System.out.print("-");

}
}
}

Output

Can't set child at 3, no parent found
Can't set child at 4, no parent found
P-R--U----

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,