Leaf nodes from Preorder of a Binary Search Tree | Stack based C # program to print leaf nodes from preorder traversal . ; Print the leaf node from the given preorder of BST . ; Since rightmost element is always leaf node . ; Driver code
using System ; using System . Collections . Generic ; public class GfG { public static void leafNode ( int [ ] preorder , int n ) { Stack < int > s = new Stack < int > ( ) ; for ( int i = 0 , j = 1 ; j < n ; i ++ , j ++ ) { bool found = false ; if ( preorder [ i ] > preorder [ j ] ) { s . Push ( preorder [ i ] ) ; } else { while ( s . Count > 0 ) { if ( preorder [ j ] > s . Peek ( ) ) { s . Pop ( ) ; found = true ; } else { break ; } } } if ( found ) { Console . Write ( preorder [ i ] + " ▁ " ) ; } } Console . WriteLine ( preorder [ n - 1 ] ) ; } public static void Main ( string [ ] args ) { int [ ] preorder = new int [ ] { 890 , 325 , 290 , 530 , 965 } ; int n = preorder . Length ; leafNode ( preorder , n ) ; } }