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





Depth of Binary Tree

LEVEL:Beginner

Description

Given an array of integers . Convert them to binary search tree and find the depth of the tree.

Input Format

First line contains n representing the no of elements in the array Next line contains n space separated values representing the array elements

Output Format

Print the depth of the Binary search tree


Example 1:

Input
5
1 5 7 8 6
Output
4
Example 2:

Input
8
1 5 7 4 2 3 5 20
Output
5
Example 3:

Input
10
1 2 3 4 5 6 7 8 9 10
Output
10

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)create another class binary tree
Step-v)create a public method which return Node and takes root,node of Node type as arguments
Step-vi)if root is null assign node to root and return node
Step-vii)if data of root is less than data of node go to next step else go to ix
Step-viii)if right of root is null assign node to root right else call the insert method passing root.right and node as argument
Step-ix)if left of root is null assign node to root left else call the insert method passing root.left and node as argument
Step-x)return root
(now we are done with the insert method)
Step-xi)create a method depth which takes node of type Node as argument
Step-xii)if node equal to null return 0
Step-xiii)else go to next steps
Step-xiv)call the depth function passing node.left as argument and store the result in ldepth
Step-xv)call the depth function passing node.right as argument and store the result in rdepth
Step-xvi)if ldepth is greater than rdepth return ldepth+1 else return rdepth +1
(we are done with the depth method)
Step-xvii)in method take the input n which tells the no of elements in the array
Step-xviii)read the n integers and store it in the array
Step-xix)traverse the array and send elements to insert function to construct the binary tree
Step-xx)now call the depth function and print the result

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