Challenge - 5 Problems
LCA Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateFind the Lowest Common Ancestor (LCA) output
What is the output of the following code that finds the LCA of nodes 5 and 1 in the given binary tree?
DSA C
struct Node {
int val;
struct Node* left;
struct Node* right;
};
struct Node* lca(struct Node* root, int p, int q) {
if (!root) return NULL;
if (root->val == p || root->val == q) return root;
struct Node* left = lca(root->left, p, q);
struct Node* right = lca(root->right, p, q);
if (left && right) return root;
return left ? left : right;
}
// Tree:
// 3
// / \
// 5 1
// / \ / \
// 6 2 0 8
// / \
// 7 4
// Call: lca(root, 5, 1)
// Output the value of the LCA node found.Attempts:
2 left
💡 Hint
The LCA is the lowest node that has both nodes as descendants.
✗ Incorrect
Nodes 5 and 1 are children of 3, so 3 is their lowest common ancestor.
❓ Predict Output
intermediateLCA output when one node is ancestor of the other
What is the output of the code when finding the LCA of nodes 5 and 4 in the same binary tree?
DSA C
/* Same Node struct and lca function as before */ // Call: lca(root, 5, 4) // Output the value of the LCA node found.
Attempts:
2 left
💡 Hint
If one node is ancestor of the other, the ancestor is the LCA.
✗ Incorrect
Node 5 is an ancestor of node 4, so the LCA is node 5 itself.
🔧 Debug
advancedIdentify the error in LCA function
What error will the following LCA function cause when called with nodes not present in the tree?
DSA C
struct Node* lca(struct Node* root, int p, int q) { if (!root) return NULL; if (root->val == p || root->val == q) return root; struct Node* left = lca(root->left, p, q); struct Node* right = lca(root->right, p, q); if (left && right) return root; return left ? left : right; } // Call: lca(root, 10, 11) where 10 and 11 are not in tree
Attempts:
2 left
💡 Hint
Check what happens when nodes are not found in either subtree.
✗ Incorrect
The function returns NULL safely if neither node is found; no error occurs.
🧠 Conceptual
advancedUnderstanding LCA in Binary Tree vs Binary Search Tree
Which statement correctly distinguishes the LCA approach in a Binary Tree vs a Binary Search Tree (BST)?
Attempts:
2 left
💡 Hint
BST has ordered values, Binary Tree does not.
✗ Incorrect
BST property allows LCA search by comparing values; Binary Tree requires full subtree search.
🚀 Application
expertLCA in a Binary Tree with Parent Pointers
Given a binary tree where each node has a pointer to its parent, which approach is the most efficient to find the LCA of two nodes p and q?
Attempts:
2 left
💡 Hint
Parent pointers allow upward traversal without root access.
✗ Incorrect
Storing ancestors of one node and checking the other node's ancestors is efficient and uses O(h) time and space, where h is tree height.
