Created
January 9, 2023 17:00
-
-
Save ILoveBacteria/88f6033f552b9b8bcbd274b92f4f3722 to your computer and use it in GitHub Desktop.
This method counts the number of sub trees from a custom root
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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