Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the height of a binary tree recursively.
DSA Javascript
function height(node) {
if (node === null) {
return 0;
}
return 1 + Math.max(height(node.left), height(node[1]));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using node.left twice instead of node.right
Using node.parent which is not part of height calculation
✗ Incorrect
The height of a binary tree is 1 plus the maximum height of its left and right subtrees. We already have height(node.left), so the other subtree is node.right.
2fill in blank
mediumComplete the code to check if the node is null before calculating height.
DSA Javascript
function height(node) {
if (node [1] null) {
return 0;
}
return 1 + Math.max(height(node.left), height(node.right));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== which reverses the logic
Using loose equality == which can cause unexpected results
✗ Incorrect
We check if node is exactly null to stop recursion and return 0 height for empty subtree.
3fill in blank
hardFix the error in the recursive call to height for the right subtree.
DSA Javascript
function height(node) {
if (node === null) {
return 0;
}
return 1 + Math.max(height(node.left), height(node[1]));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Typos like '.leftt' or '.rigt'
Using '.parent' which is not a child node
✗ Incorrect
The correct property for the right child is node.right. Misspelled properties cause runtime errors.
4fill in blank
hardFill both blanks to create a function that returns the height of a binary tree using recursion.
DSA Javascript
function height(node) {
if (node [1] null) {
return 0;
}
return 1 + Math.max(height(node[2]), height(node.right));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of === in null check
Using '.parent' instead of '.left' for child node
✗ Incorrect
Check if node is exactly null, then recursively get height of left and right children.
5fill in blank
hardFill all three blanks to complete the height function with correct null check and recursive calls.
DSA Javascript
function height(node) {
if (node [1] null) {
return 0;
}
return 1 + Math.max(height(node[2]), height(node[3]));
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of === for null check
Swapping left and right child properties
✗ Incorrect
Use strict equality to check null, then recursively call height on left and right children.