Find Count of Single Valued Subtrees | Class containing left and right child of current node and key value ; This function increments count by number of single valued subtrees under root . It returns true if subtree under root is Singly , else false . ; Return false to indicate NULL ; Recursively count in left and right subtrees also ; If any of the subtrees is not singly , then this cannot be singly . ; If left subtree is singly and non - empty , but data doesn 't match ; Same for right subtree ; If none of the above conditions is true , then tree rooted under root is single valued , increment count and return true . ; This function mainly calls countSingleRec ( ) after initializing count as 0 ; Recursive function to count ; Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5
class Node { constructor ( item ) { this . data = item ; this . left = this . right = null ; } } class Count { constructor ( ) { this . count = 0 ; } } var root ; var ct = new Count ( ) ; function countSingleRec ( node , c ) { if ( node == null ) return true ; var left = countSingleRec ( node . left , c ) ; var right = countSingleRec ( node . right , c ) ; if ( left == false right == false ) return false ; if ( node . left != null && node . data != node . left . data ) return false ; if ( node . right != null && node . data != node . right . data ) return false ; c . count ++ ; return true ; } function countSingle ( ) { return countSingle ( root ) ; } function countSingle ( node ) { countSingleRec ( node , ct ) ; return ct . count ; } root = new Node ( 5 ) ; root . left = new Node ( 4 ) ; root . right = new Node ( 5 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 4 ) ; root . right . right = new Node ( 5 ) ; document . write ( " " + countSingle ( root ) ) ;