Check given array of size n can represent BST of n levels or not | C # 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
using System ; class GFG { public class Node { public int key ; public 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 bool isBST ( Node root , int min , int max ) { if ( root == null ) { return true ; } if ( root . key < min . key > max ) { return false ; } return ( isBST ( root . left , min , ( root . key ) - 1 ) && isBST ( root . right , ( root . key ) + 1 , max ) ) ; } static bool canRepresentNLevelBST ( int [ ] arr , int n ) { Node root = createNLevelTree ( arr , n ) ; return isBST ( root , int . MinValue , int . MaxValue ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 512 , 330 , 78 , 11 , 8 } ; int n = arr . Length ; if ( canRepresentNLevelBST ( arr , n ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }