Find Count of Single Valued Subtrees | C # program to 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 ; Driver program to test above functions ; Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5
using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class Count { public int count = 0 ; } public class BinaryTree { public Node root ; public Count ct = new Count ( ) ; public virtual bool countSingleRec ( Node node , Count c ) { if ( node == null ) { return true ; } bool left = countSingleRec ( node . left , c ) ; bool 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 ; } public virtual int countSingle ( ) { return countSingle ( root ) ; } public virtual int countSingle ( Node node ) { countSingleRec ( node , ct ) ; return ct . count ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 5 ) ; tree . root . left = new Node ( 4 ) ; tree . root . right = new Node ( 5 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 4 ) ; tree . root . right . right = new Node ( 5 ) ; Console . WriteLine ( " The ▁ count ▁ of ▁ single ▁ valued ▁ sub ▁ trees ▁ is ▁ : ▁ " + tree . countSingle ( ) ) ; } }