Array ( [0] => [1] => questions [2] => Popular-Algorithms [3] => Convert-Array-to-Binary-Tree ) Popular Algorithms | Convert Array to Binary Tree | THE INQUISITIVE





Convert Array to Binary Tree

LEVEL:Beginner

Description

Given an array. Arrange them in the form of binary tree and print in inorder fashion.

Input Format

First line contains N representing the no of elements in the array next line contains N space separated integers which are the elements.

Output Format

Convert the given array to binary tree and print in Inorder fashion.


Example 1:

Input
5
1 2 3 4 5
Output
4 2 5 1 3
Example 2:

Input
8
6 5 7 8 9 2 10 5
Output
5 8 5 9 6 2 7 10
Example 3:

Input
10
62 32 58 41 25 622 245 20 87 45
Output
20 41 87 32 45 25 62 622 58 245

oops

Login to see Discussion




Approach

Step-i) Create a class Node with instances data of int type and left,right of Node type
Step-ii)create a default constructor which initializes left and right to null
Step-iii)create a constructor which accepts key as argument and assigns it to data
(this class is used to create a node of the tree)
Step-iv)now create a another class Tree
Step-v)create a variable root of Node type
Step-vii)now create a method insert which accepts arr, root and i as arguments
Step-viii)if i is less than length of arr go to next steps else go to xiii
Step-ix)create temp of type Node and initiaize it's data to array[i]
Step-x) assign temp to root
Step-xi)call the insert function passing arr,root and 2*i+1 as argument and store the result in root.left
Step-xii)call the insert function passing arr,root and 2*i+2 as argument and store the result in root.right
Step-xiii)return root
Step-xiv)create a method inorder which accepts root of Node type as argument
Step-xv)if root not equal to null go to next steps
Step-xvi)call the inorder function passing root.left as argument
Step-xvii)print the data part of root
Step-xviii)call the inorder function passing root.right as argument
Step-xix)in main method take the input n
Step-xx)then read the elements of array
Step-xxi) create a object of Tree class and name it as tree
Step-xxii) call the insert method of Tree passing arr , tree.root and 0 as arguments and store the result in tree.root
Step-xxiii)now call the inorder function to print the output

Time Complexity: O(n)
Space Complexity: O(1)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution