Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the current node is a leaf node.
DSA C++
if (root->left == nullptr && root->right == [1]) { return sum == root->val; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or NULL instead of nullptr.
Checking only one child pointer.
✗ Incorrect
A leaf node has no left or right children, so both should be nullptr.
2fill in blank
mediumComplete the code to recursively check the left subtree for the path sum.
DSA C++
if (root->left != nullptr) { if (hasPathSum(root->left, sum - [1])) { return true; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting sum instead of root->val.
Using the child's value instead of current node's value.
✗ Incorrect
We subtract the current node's value from sum before checking the subtree.
3fill in blank
hardFix the error in the base case to handle null nodes correctly.
DSA C++
if (root == [1]) { return false; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using NULL or 0 instead of nullptr.
Checking root against root itself.
✗ Incorrect
The base case should check if root is nullptr to avoid dereferencing null pointers.
4fill in blank
hardFill both blanks to recursively check left and right subtrees for the path sum.
DSA C++
return hasPathSum(root->[1], sum - root->val) || hasPathSum(root->[2], sum - root->val);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using val or parent instead of left or right.
Not subtracting root->val from sum.
✗ Incorrect
We check both left and right children recursively for the path sum.
5fill in blank
hardFill all three blanks to complete the hasPathSum function.
DSA C++
bool hasPathSum(TreeNode* root, int sum) {
if (root == [1]) return false;
if (root->left == nullptr && root->right == nullptr) {
return sum == root->[2];
}
return hasPathSum(root->[3], sum - root->val) || hasPathSum(root->right, sum - root->val);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong pointer names or values.
Not handling null root correctly.
✗ Incorrect
Check for null root, compare sum with root->val at leaf, and recurse left and right.