Check if removing an edge can divide a Binary Tree in two halves | Javascript program to check if there exist an edge whose removal creates two trees of same size ; To calculate size of tree with given root ; This function returns true if there is an edge whose removal can divide the tree in two halves n is size of tree ; Base cases ; Check for root ; Check for rest of the nodes ; This function mainly uses checkRec ( ) ; Count total nodes in given tree ; Now recursively check all nodes ; Driver code
class Node { constructor ( key ) { this . key = key ; this . left = this . right = null ; } } function count ( node ) { if ( node == null ) return 0 ; return count ( node . left ) + count ( node . right ) + 1 ; } function checkRec ( node , n ) { if ( node == null ) return false ; if ( count ( node ) == n - count ( node ) ) return true ; return checkRec ( node . left , n ) || checkRec ( node . right , n ) ; } function check ( node ) { let n = count ( node ) ; return checkRec ( node , n ) ; } let root = new Node ( 5 ) ; root . left = new Node ( 1 ) ; root . right = new Node ( 6 ) ; root . left . left = new Node ( 3 ) ; root . right . left = new Node ( 7 ) ; root . right . right = new Node ( 4 ) ; if ( check ( root ) == true ) document . write ( " " ) ; else document . write ( " " ) ;