Complete the code to return the total number of nodes in the binary tree.
public int countNodes(TreeNode root) {
if (root == null) {
return [1];
}
return 1 + countNodes(root.left) + countNodes(root.right);
}When the node is null, it means no node exists, so return 0.
Complete the code to count nodes by recursively adding left and right subtree counts.
return 1 + countNodes([1]) + countNodes(root.right);
We add the count of nodes in the left subtree by calling countNodes on root.left.
Fix the error in the recursive call to count the right subtree nodes.
return 1 + countNodes(root.left) + countNodes([1]);
We must call countNodes on root.right to count nodes in the right subtree.
Fill both blanks to complete the base case and recursive calls for counting nodes.
if ([1] == null) { return [2]; }
Check if root is null, then return 0 because no nodes exist there.
Fill all three blanks to complete the recursive function counting total nodes.
public int countNodes(TreeNode [1]) { if ([2] == null) { return 0; } return 1 + countNodes([3]) + countNodes([1].right); }
The function parameter is named root. We check if root is null, then recursively count nodes in root.left and root.right.
