intcountAllNodes(struct Node *ptr) {// Variables to obtain nodes is left and right subtreeint leftNodes, rightNodes;if (ptr) { leftNodes =countAllNodes(ptr -> left); rightNodes =countAllNodes(ptr -> right);return leftNodes + rightNodes +1; }return0;}
Count Nodes Having Both Children (Degree 2) :
intcountTwoChildren(struct Node *ptr) {// Variables to obtain nodes is left and right subtreeint leftNodes, rightNodes;if (ptr) { leftNodes =countTwoChildren(ptr -> left); rightNodes =countTwoChildren(ptr -> right);// Check if both children are presentif (ptr -> left &&ptr -> right) {return leftNodes + rightNodes +1; } else {return leftNodes + rightNodes; } }return0;}
Count Nodes Having One or More Children (Degree 1 or 2) :
intcountOneOrMore(struct Node *ptr) {// Variables to obtain nodes is left and right subtreeint leftNodes, rightNodes;if (ptr) { leftNodes =countOneOrMore(ptr -> left); rightNodes =countOneOrMore(ptr -> right);// Check if atleast one child is presentif (ptr -> left ||ptr -> right) {return leftNodes + rightNodes +1; } else {return leftNodes + rightNodes; } }return0;}
Count Nodes Having Exactly One Child (Degree 1) :
intcountOneChild(struct Node *ptr) {// Variables to obtain nodes is left and right subtreeint leftNodes, rightNodes;if (ptr) { leftNodes =countOneChild(ptr -> left); rightNodes =countOneChild(ptr -> right);// Perform XOR operation to check if only child is presentif (ptr -> left ^ptr -> right) {return leftNodes + rightNodes +1; } else {return leftNodes + rightNodes; } }return0;}
Count Leaf Nodes (Degree 0) :
intcountLeafNodes(struct Node *ptr) {// Variables to obtain nodes is left and right subtreeint leftNodes, rightNodes;if (ptr) { leftNodes =countLeafNodes(ptr -> left); rightNodes =countLeafNodes(ptr -> right);// Check if both children are NULLif (!(ptr -> left) &&!(ptr -> right)) {return leftNodes + rightNodes +1; } else {return leftNodes + rightNodes; } }return0;}