Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the total number of nodes in the binary tree.
DSA Typescript
function countNodes(root: TreeNode | null): number {
if (root === null) return [1];
return 1 + countNodes(root.left) + countNodes(root.right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 instead of 0 for null nodes.
Returning null which causes errors.
✗ Incorrect
When the node is null, it means no node exists, so count is 0.
2fill in blank
mediumComplete the code to check if the current node is null before counting.
DSA Typescript
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left or right child instead of the current node.
Checking against a wrong variable.
✗ Incorrect
We check if the current node root is null to stop recursion.
3fill in blank
hardFix the error in the recursive call to count left subtree nodes.
DSA Typescript
function countNodes(root: TreeNode | null): number {
if (root === null) return 0;
return 1 + countNodes([1]) + countNodes(root.right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the whole root again causing infinite recursion.
Passing right child instead of left child.
✗ Incorrect
To count left subtree nodes, we call countNodes(root.left).
4fill in blank
hardFill both blanks to complete the function that counts nodes using recursion.
DSA Typescript
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes([2]) + countNodes(root.right);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking left or right child instead of root for null.
Passing wrong child node in recursive call.
✗ Incorrect
The base case checks if root is null, then recursively count left subtree with root.left.
5fill in blank
hardFill all three blanks to complete the recursive function counting all nodes in the binary tree.
DSA Typescript
function countNodes(root: TreeNode | null): number {
if ([1] === null) return 0;
return 1 + countNodes([2]) + countNodes([3]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null instead of root for base case.
Mixing left and right child nodes in recursive calls.
✗ Incorrect
Check if root is null, then count nodes in left subtree root.left and right subtree root.right.