Count the Nodes in a BST
Count the Nodes in a BST
Complete the private helper size(Node node) so that size() returns how many values are stored in the tree.
Reminder: thinking about a tree recursively. A tree is either empty, or it is one node with a left subtree and a right subtree hanging below it, and each of those subtrees is a tree of its own. Most tree methods follow that exact shape: answer the empty case directly, otherwise combine this node with the answers for its two subtrees.
8
/ \
3 10
/ \ \
1 6 14For counting: an empty tree holds 0 nodes. Any other tree holds this one node plus however many its left subtree holds plus however many its right subtree holds. In the picture the subtree under 3 holds 3 nodes and the subtree under 10 holds 2, so the whole tree holds 1 + 3 + 2. Unlike a search, counting has to visit BOTH sides of every node. insert ignores a value that is already in the tree, so a value is never counted twice.
Requirements: 1. Return 0 when node is null. 2. Otherwise return 1 plus the size of the left subtree plus the size of the right subtree. 3. Use recursion, not a loop or a counter field.
The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.
Do NOT write a main method.
Expected Output:
0 6 6 7
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...