Continuous Tree | CPP Code to check if the tree is continuous or not ; Node structure ; Function to check if the tree is continuous or not ; If root is Null then tree isn 't Continuous ; BFS Traversal ; Move to left child ; if difference between parent and child is equal to 1 then do continue otherwise make flag = 0 and break ; Move to right child ; if difference between parent and child is equal to 1 then do continue otherwise make flag = 0 and break ; Driver Code ; Constructing the Tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int val ; node * left ; node * right ; node ( ) : val ( 0 ) , left ( nullptr ) , right ( nullptr ) { } node ( int x ) : val ( x ) , left ( nullptr ) , right ( nullptr ) { } node ( int x , node * left , node * right ) : val ( x ) , left ( left ) , right ( right ) { } } ; bool continuous ( struct node * root ) { if ( root == NULL ) return false ; int flag = 1 ; queue < struct node * > Q ; Q . push ( root ) ; node * temp ; while ( ! Q . empty ( ) ) { temp = Q . front ( ) ; Q . pop ( ) ; if ( temp -> left ) { if ( abs ( temp -> left -> val - temp -> val ) == 1 ) Q . push ( temp -> left ) ; else { flag = 0 ; break ; } } if ( temp -> right ) { if ( abs ( temp -> right -> val - temp -> val ) == 1 ) Q . push ( temp -> right ) ; else { flag = 0 ; break ; } } } if ( flag ) return true ; else return false ; } int main ( ) { struct node * root = new node ( 3 ) ; root -> left = new node ( 2 ) ; root -> right = new node ( 4 ) ; root -> left -> left = new node ( 1 ) ; root -> left -> right = new node ( 3 ) ; root -> right -> right = new node ( 5 ) ; if ( continuous ( root ) ) cout << " True STRNEWLINE " ; else cout << " False STRNEWLINE " ; return 0 ; }