Complete the code to return the total number of nodes in the binary tree.
function countNodes(root: TreeNode | null): number {
if (root === null) return [1];
return 1 + countNodes(root.left) + countNodes(root.right);
}When the node is null, it means no node exists, so count is 0.
Complete the code to check if the current node is null before counting.
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}We check if the current node root is null to stop recursion.
Fix the error in the recursive call to count left subtree nodes.
function countNodes(root: TreeNode | null): number {
if (root === null) return 0;
return 1 + countNodes([1]) + countNodes(root.right);
}To count left subtree nodes, we call countNodes(root.left).
Fill both blanks to complete the function that counts nodes using recursion.
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes([2]) + countNodes(root.right);
}The base case checks if root is null, then recursively count left subtree with root.left.
Fill all three blanks to complete the recursive function counting all nodes in the binary tree.
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes([2]) + countNodes([3]);
}Check if root is null, then count nodes in left subtree root.left and right subtree root.right.
