Check given array of size n can represent BST of n levels or not | Java program to Check given array can represent BST or not ; structure for Binary Node ; To create a Tree with n levels . We always insert new node to left if it is less than previous value . ; Please refer below post for details of this function . www . geeksforgeeks . org / a - program - to - check - if - a - binary - tree - is - bst - or - not / https : ; Allow only distinct values ; Returns tree if given array of size n can represent a BST of n levels . ; Driver code
class GFG { static class Node { int key ; Node right , left ; } ; static Node newNode ( int num ) { Node temp = new Node ( ) ; temp . key = num ; temp . left = null ; temp . right = null ; return temp ; } static Node createNLevelTree ( int arr [ ] , int n ) { Node root = newNode ( arr [ 0 ] ) ; Node temp = root ; for ( int i = 1 ; i < n ; i ++ ) { if ( temp . key > arr [ i ] ) { temp . left = newNode ( arr [ i ] ) ; temp = temp . left ; } else { temp . right = newNode ( arr [ i ] ) ; temp = temp . right ; } } return root ; } static boolean isBST ( Node root , int min , int max ) { if ( root == null ) { return true ; } if ( root . key < min root . key > max ) { return false ; } return ( isBST ( root . left , min , ( root . key ) - 1 ) && isBST ( root . right , ( root . key ) + 1 , max ) ) ; } static boolean canRepresentNLevelBST ( int arr [ ] , int n ) { Node root = createNLevelTree ( arr , n ) ; return isBST ( root , Integer . MIN_VALUE , Integer . MAX_VALUE ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 512 , 330 , 78 , 11 , 8 } ; int n = arr . length ; if ( canRepresentNLevelBST ( arr , n ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }