Binary Tree (Array Implementation) - GeeksforGeeks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks


Binary Tree (Array implementation)
Last Updated: 03-09-2019

Talking about representation, trees can be represented in two way:


1) Dynamic Node Representation (Linked Representation).
2) Array Representation (Sequential Representation).

We are going to talk about the sequential representation of the trees.


To represent tree using an array, numbering of nodes can start either from 0–(n-1) or 1– n.

A(0)
/ \
B(1) C(2)
/ \ \
D(3) E(4) F(6)
OR,
A(1)
/ \
B(2) C(3)
/ \ \
D(4) E(5) F(7)

For rst case(0—n-1),


if (say)father=p;
then left_son=(2*p)+1;
and right_son=(2*p)+2;

For second case(1—n),


if (say)father=p;
then left_son=(2*p);
and right_son=(2*p)+1;
where father, left_son and right_son are the values of indices of the array.

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 1/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

Recommended: Please try your approach on {IDE} rst, before moving on to the
solution.

C++

// C++ implementation of tree using array


// numbering starting from 0 to n-1.
#include<bits/stdc++.h>
using namespace std;
char tree[10];
int root(char key)
{
if(tree[0] != '\0')
cout << "Tree already had root";
else
tree[0] = key;
return 0;
}

int set_left(char key, int parent)


{
if(tree[parent] == '\0')
cout << "\nCan't set child at"
<< (parent * 2) + 1
<< " , no parent found";
else
tree[(parent * 2) + 1] = key;
return 0;
}

int set_right(char key, int parent)


{
if(tree[parent] == '\0')
cout << "\nCan't set child at"
<< (parent * 2) + 2
<< " , no parent found";
else
tree[(parent * 2) + 2] = key;
return 0;
}

int print_tree()
{
cout << "\n";
for(int i = 0; i < 10; i++)
https://www.geeksforgeeks.org/binary-tree-array-implementation/ 2/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

{
if(tree[i] != '\0')
cout << tree[i];
else
cout << "-";
}
return 0;
}

// Driver Code
int main()
{
root('A');
//insert_left('B',0);
set_right('C', 0);
set_left('D', 1);
set_right('E', 1);
set_right('F', 2);
print_tree();
return 0;
}

// This code is contributed by


// Gaurav_Kumar_Raghav

Java

// JAVA implementation of tree using array


// numbering starting from 0 to n-1.
import java.util.*;
import java.lang.*;
import java.io.*;

class Tree {
public static void main(String[] args)
{
Array_imp obj = new Array_imp();
obj.Root("A");
// obj.set_Left("B", 0);
obj.set_Right("C", 0);
obj.set_Left("D", 1);
obj.set_Right("E", 1);
obj.set_Left("F", 2);
obj.print_Tree();
}
}

class Array_imp {
static int root = 0;
static String[] str = new String[10];

/*create root*/
public void Root(String key)
{
https://www.geeksforgeeks.org/binary-tree-array-implementation/ 3/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

str[0] = key;
}

/*create left son of root*/


public void set_Left(String key, int root)
{
int t = (root * 2) + 1;

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

/*create right son of root*/


public void set_Right(String key, int root)
{
int t = (root * 2) + 2;

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

public void print_Tree()


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

C#

// C# implementation of tree using array


// numbering starting from 0 to n-1.
using System;

public class Tree {


public static void Main(String[] args)
{
Array_imp obj = new Array_imp();
obj.Root("A");
// obj.set_Left("B", 0);
obj.set_Right("C", 0);

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 4/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

obj.set_Left("D", 1);
obj.set_Right("E", 1);
obj.set_Left("F", 2);
obj.print_Tree();
}
}

class Array_imp {
static int root = 0;
static String[] str = new String[10];

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

/*create left son of root*/


public void set_Left(String key, int root)
{
int t = (root * 2) + 1;

if (str[root] == null) {
Console.Write("Can't set child at {0}, no parent found\n", t);
}
else {
str[t] = key;
}
}

/*create right son of root*/


public void set_Right(String key, int root)
{
int t = (root * 2) + 2;

if (str[root] == null) {
Console.Write("Can't set child at {0}, no parent found\n", t);
}
else {
str[t] = key;
}
}

public void print_Tree()


{
for (int i = 0; i < 10; i++) {
if (str[i] != null)
Console.Write(str[i]);
else
Console.Write("-");
}
}
}

// This code contributed by Rajput-Ji

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 5/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

Output:
Can't set child at 3, no parent found
Can't set child at 4, no parent found
A-C--F----

Note – Please refer this if you want to construct tree from the given parent array.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with
the DSA Self Paced Course at a student-friendly price and become industry ready.

Recommended Posts:
Implementation of Binary Search Tree in Javascript
Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Minimum swap required to convert binary tree to binary search tree
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Find the median array for Binary tree
Check whether a binary tree is a full binary tree or not | Iterative Approach
Construct Binary Tree from given Parent Array representation
Check if an array represents Inorder of Binary Search tree or not
Shortest path between two nodes in array like representation of binary tree
Find Height of Binary Tree represented by Parent array
Convert a Binary Tree to Threaded binary tree | Set 2 (E cient)
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Check if a given array can represent Preorder Traversal of Binary Search Tree

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 6/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

Construct a complete binary tree from given array in level order fashion
Construct Binary Tree from given Parent Array representation | Iterative Approach
Check if the given array can represent Level Order Traversal of Binary Search Tree
Create a binary tree from post order traversal and leaf node array
BK-Tree | Introduction & Implementation
Palindromic Tree | Introduction & Implementation

sanjal_katiyar
Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See
your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you nd anything incorrect by clicking on the "Improve Article"
button below.

Improved By : Sachin Jain 1, diegoolalde, Rajput-Ji, gaurav_kumar_raghav

Article Tags : Arrays Java Technical Scripter Tree Binary Tree Java-Array-Programs

Practice Tags : Arrays Java Tree


21

2
To-do Done
Based on 33 vote(s)

Feedback/ Suggest Improvement Improve Article

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 7/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

How to begin? Videos

@geeksforgeeks , Some rights reserved

https://www.geeksforgeeks.org/binary-tree-array-implementation/ 9/9
9/8/2020 Binary Tree (Array implementation) - GeeksforGeeks

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

15 Comments GeeksforGeeks 🔒 
1 Login

 Recommend t Tweet f Share Sort by Newest

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Vishal Sinha • 3 months ago


Output shown will have one more dash between C and F as per
the code.
△ ▽ • Reply • Share ›

Susmit Singh • 4 months ago


H i th PYTHON CODE

5th Floor, A-118,


 Sector-136, Noida, Uttar Pradesh - 201305
 feedback@geeksforgeeks.org

Company Learn
About Us Algorithms
Careers Data Structures
Privacy Policy Languages
Contact Us CS Subjects
Video Tutorials

Practice Contribute
Courses Write an Article
Company-wise Write Interview Experience
Topic-wise Internships
https://www.geeksforgeeks.org/binary-tree-array-implementation/ 8/9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy