Continuous Tree | Java program to check if a tree is continuous or not ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and null left and right pointers . ; Function to check tree is continuous or not ; if next node is empty then return true ; if current node is leaf node then return true because it is end of root to leaf path ; If left subtree is empty , then only check right ; If right subtree is empty , then only check left ; If both left and right subtrees are not empty , check everything ; Driver program to test mirror ( )
import java . util . * ; class solution { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static boolean treeContinuous ( Node ptr ) { if ( ptr == null ) return true ; if ( ptr . left == null && ptr . right == null ) return true ; if ( ptr . left == null ) return ( Math . abs ( ptr . data - ptr . right . data ) == 1 ) && treeContinuous ( ptr . right ) ; if ( ptr . right == null ) return ( Math . abs ( ptr . data - ptr . left . data ) == 1 ) && treeContinuous ( ptr . left ) ; return Math . abs ( ptr . data - ptr . left . data ) == 1 && Math . abs ( ptr . data - ptr . right . data ) == 1 && treeContinuous ( ptr . left ) && treeContinuous ( ptr . right ) ; } public static void main ( String args [ ] ) { Node root = newNode ( 3 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 4 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 3 ) ; root . right . right = newNode ( 5 ) ; if ( treeContinuous ( root ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }