Skip to content

Instantly share code, notes, and snippets.

@ILoveBacteria
Created January 9, 2023 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ILoveBacteria/88f6033f552b9b8bcbd274b92f4f3722 to your computer and use it in GitHub Desktop.
Save ILoveBacteria/88f6033f552b9b8bcbd274b92f4f3722 to your computer and use it in GitHub Desktop.
This method counts the number of sub trees from a custom root
class BST_Tree {
Node nodeHead;
/**
* @param customRoot The custom node is a root that will be calculate number of sub trees from that
*/
int countSubTree(Node customRoot) {
if (customRoot.left != null && customRoot.right != null) {
int subTreeLeft = countSubTree(customRoot.left);
int subTreeRight = countSubTree(customRoot.right);
return (subTreeLeft * subTreeRight) + (subTreeLeft + subTreeRight) + 1;
}
if (customRoot.left != null) {
int subTreeLeft = countSubTree(customRoot.left);
return subTreeLeft + 1;
}
if (customRoot.right != null) {
int subTreeRight = countSubTree(customRoot.right);
return subTreeRight + 1;
}
return 1;
}
}
class Node {
int data;
Node left;
Node right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment