Array ( [0] => [1] => questions [2] => Arrays [3] => Number-of-Nodes-in-BST ) Popular Algorithms | Number of Nodes in BST | THE INQUISITIVE





Number of Nodes in BST

LEVEL:Beginner

Description

Given a array, convert the array to binary search tree and count the no of nodes in it

Input Format

First line contains N representing no of elements in the array Next line contains N integers representing the elements of the array.

Output Format

Convert the array to Binary Search Tree and print the no of nodes in it.


Example 1:

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

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

Input
10 
52 14 2 3 5 8 4 2 5 65
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)now create a variable count in binary tree class
Step-xii)then create a method no_of_node which takes root of Node type as argument and returns int
Step-xiii)if root is equal to null return 0
Step-xiv)if root.left not equal to null increment count by one value and call no_of_node funtion passing root.left as argument
and store it in count
Step-xv)if root.right is not equal to null increment count by one value and call no_of_node function passing root.right as
argument and store it in count
Step-xvi)return count
(now we are done with the no_of_node method)
Step-xvii)in main method take input n which tells us about no of elements in the array
Step-xviii)next store the n elements in the array
Step-xix) traverse the array and and send array elements to insert method to construct binary search tree
Step-xx)now call the method no_of_node passing root as parameter and store the answer in result
Step-xxi)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