Largest value in each level of Binary Tree | Set | C ++ implementation to print largest value in each level of Binary Tree ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to print largest value in each level of Binary Tree ; if tree is empty ; push root to the queue ' q ' ; node count for the current level ; if true then all the nodes of the tree have been traversed ; maximum element for the current level ; get the front element from ' q ' ; remove front element from ' q ' ; if true , then update ' max ' ; if left child exists ; if right child exists ; print maximum element of current level ; Driver code ; Construct a Binary Tree 4 / \ 9 2 / \ \ 3 5 7 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void largestValueInEachLevel ( Node * root ) { if ( ! root ) return ; queue < Node * > q ; int nc , max ; q . push ( root ) ; while ( 1 ) { nc = q . size ( ) ; if ( nc == 0 ) break ; max = INT_MIN ; while ( nc -- ) { Node * front = q . front ( ) ; q . pop ( ) ; if ( max < front -> data ) max = front -> data ; if ( front -> left ) q . push ( front -> left ) ; if ( front -> right ) q . push ( front -> right ) ; } cout << max << " ▁ " ; } } int main ( ) { Node * root = NULL ; root = newNode ( 4 ) ; root -> left = newNode ( 9 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 7 ) ; largestValueInEachLevel ( root ) ; return 0 ; }