Smallest value in each level of Binary Tree | C # program to print minimum element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; push the root for Change the level ; for go level by level ; for check the level ; Get top of queue ; if node == null ( Means this is boundary between two levels ) ; here queue is empty represent no element in the actual queue ; increment level ; Reset min for next level minimum value ; get Minimum in every level ; Enqueue left child ; Enqueue right child ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
using System ; using System . Collections . Generic ; class GFG { class Node { public int data ; public Node left , right ; } ; static int heightoftree ( Node root ) { if ( root == null ) return 0 ; int left = heightoftree ( root . left ) ; int right = heightoftree ( root . right ) ; return ( ( left > right ? left : right ) + 1 ) ; } static void printPerLevelMinimum ( Node root ) { if ( root == null ) return ; Queue < Node > q = new Queue < Node > ( ) ; q . Enqueue ( root ) ; q . Enqueue ( null ) ; int min = int . MaxValue ; int level = 0 ; while ( q . Count != 0 ) { Node node = q . Peek ( ) ; q . Dequeue ( ) ; if ( node == null ) { Console . Write ( " level ▁ " + level + " ▁ min ▁ is ▁ = ▁ " + min + " STRNEWLINE " ) ; if ( q . Count == 0 ) break ; q . Enqueue ( null ) ; level ++ ; min = int . MaxValue ; continue ; } if ( min > node . data ) min = node . data ; if ( node . left != null ) { q . Enqueue ( node . left ) ; } if ( node . right != null ) { q . Enqueue ( node . right ) ; } } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void Main ( String [ ] args ) { Node root = newNode ( 7 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 2 ) ; root . right . right = newNode ( 1 ) ; Console . Write ( " Every ▁ Level ▁ minimum ▁ is " + " STRNEWLINE " ) ; printPerLevelMinimum ( root ) ; } }