Bird
Raised Fist0
DSA C++programming~10 mins

Lowest Common Ancestor in Binary Tree in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Lowest Common Ancestor in Binary Tree
Start at root node
↓
Check if root is null or matches p or q
Yes↓
Return root
No↓
Recurse left subtree
↓
Recurse right subtree
↓
If left and right both non-null
↓
Return root as LCA
↓
Return non-null child (left or right)
Start from root, recursively search left and right subtrees for nodes p and q. If both sides return non-null, root is LCA. Otherwise, return the non-null side.
Execution Sample
DSA C++
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  if (!root || root == p || root == q) return root;
  TreeNode* left = lowestCommonAncestor(root->left, p, q);
  TreeNode* right = lowestCommonAncestor(root->right, p, q);
  if (left && right) return root;
  return left ? left : right;
}
Finds the lowest common ancestor of nodes p and q in a binary tree by recursive search.
Execution Table
StepOperationNode VisitedLeft ResultRight ResultReturn ValueVisual State
1Start at root3???3
2Check root == p or q3??No3
3Recurse left subtree5???3 -> 5
4Check root == p or q5??No3 -> 5
5Recurse left subtree6???3 -> 5 -> 6
6Check root == p or q6??Yes (matches p)3 -> 5 -> 6
7Return node 666?63 -> 5 -> 6
8Recurse right subtree2???3 -> 5 -> 6, 2
9Check root == p or q2??No3 -> 5 -> 6, 2
10Recurse left subtree7???3 -> 5 -> 6, 2 -> 7
11Check root == p or q7??Yes (matches q)3 -> 5 -> 6, 2 -> 7
12Return node 77?773 -> 5 -> 6, 2 -> 7
13Recurse right subtree4???3 -> 5 -> 6, 2 -> 7, 4
14Check root == p or q4??No3 -> 5 -> 6, 2 -> 7, 4
15Recurse left subtreenullnull?null3 -> 5 -> 6, 2 -> 7, 4
16Return nullnullnull?null3 -> 5 -> 6, 2 -> 7, 4
17Recurse right subtreenull?nullnull3 -> 5 -> 6, 2 -> 7, 4
18Return nullnull?nullnull3 -> 5 -> 6, 2 -> 7, 4
19Return left or right4nullnullnull3 -> 5 -> 6, 2 -> 7, 4
20Return left or right27null73 -> 5 -> 6, 2 -> 7
21Return left or right56733
22Both left and right non-null, return root36733
💡 At root 3, left subtree returned node 6, right subtree returned node 7, so root 3 is LCA.
Variable Tracker
VariableStartAfter Step 6After Step 12After Step 20Final
root36733
left?6666
right??777
Return Value?6773
Key Moments - 3 Insights
Why do we return root immediately if root matches p or q?
Because if root is p or q, it could be the ancestor or one of the nodes itself. See step 6 where root 6 matches p and returns immediately.
Why do we return root when both left and right recursive calls are non-null?
Because it means p and q are found in different subtrees, so current root is their lowest common ancestor. See step 22 where both left=6 and right=7 are non-null, so root 3 is returned.
What if one subtree returns null?
We return the non-null subtree result because both p and q are in that subtree or one is ancestor of the other. See step 20 where left=7 and right=null returns 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 6, what is the return value and why?
AReturns node 6 because root matches p
BReturns null because no match
CReturns node 3 because root is ancestor
DReturns node 7 because it matches q
💡 Hint
Check step 6 in execution_table where root == p returns root
At which step does the function determine the lowest common ancestor?
AStep 12
BStep 20
CStep 22
DStep 7
💡 Hint
Look for step where both left and right are non-null and root is returned
If node q was not in the tree, how would the return value at step 22 change?
AIt would return node 6
BIt would return null
CIt would return node 3
DIt would return node 7
💡 Hint
If one subtree returns null, return the other subtree's result as per step 20
Concept Snapshot
Lowest Common Ancestor (LCA) finds the deepest node that is ancestor of both p and q.
Use recursion: if root is null or matches p/q, return root.
Recurse left and right subtrees.
If both sides return non-null, root is LCA.
Else return the non-null side.
This works for any binary tree, not just BST.
Full Transcript
The Lowest Common Ancestor in a binary tree is found by starting at the root and recursively searching for nodes p and q in the left and right subtrees. If the current root is null or matches either p or q, it returns the root immediately. Otherwise, it searches left and right subtrees. If both recursive calls return non-null, it means p and q are found in different subtrees, so the current root is their lowest common ancestor. If only one side returns non-null, that side is returned upwards. This process continues until the LCA is found or the search ends. The execution table traces each step visiting nodes, checking conditions, and returning values, showing how the recursion unfolds and combines results to find the LCA.

Practice

(1/5)
1. What is the Lowest Common Ancestor (LCA) of two nodes in a binary tree?
easy
A. The deepest node that is an ancestor of both nodes
B. The root node of the binary tree
C. The node with the smallest value between the two nodes
D. The node that appears first in an inorder traversal

Solution

  1. Step 1: Understand the definition of LCA

    The Lowest Common Ancestor is the deepest node in the tree that has both given nodes as descendants (a node can be a descendant of itself).
  2. Step 2: Differentiate from other nodes

    It is not necessarily the root or the node with smallest value, but the common ancestor closest to the two nodes.
  3. Final Answer:

    The deepest node that is an ancestor of both nodes -> Option A
  4. Quick Check:

    LCA = deepest common ancestor [OK]
Hint: LCA is the lowest node common to both paths [OK]
Common Mistakes:
  • Confusing LCA with root node
  • Choosing node by value instead of position
  • Thinking LCA is the first visited node in traversal
2. Which of the following is the correct C++ function signature to find LCA in a binary tree node structure?
easy
A. int findLCA(int root, int n1, int n2);
B. TreeNode* findLCA(TreeNode* root, int n1, int n2);
C. void findLCA(TreeNode root, int n1, int n2);
D. TreeNode findLCA(TreeNode root, int n1, int n2);

Solution

  1. Step 1: Analyze parameter types

    The function should accept a pointer to the root node and two integer values representing node keys.
  2. Step 2: Analyze return type

    The function returns a pointer to the TreeNode representing the LCA, so return type must be TreeNode*.
  3. Final Answer:

    TreeNode* findLCA(TreeNode* root, int n1, int n2); -> Option B
  4. Quick Check:

    Function signature with pointers and correct return type [OK]
Hint: LCA function returns pointer to TreeNode [OK]
Common Mistakes:
  • Using value instead of pointer for root
  • Returning int instead of TreeNode*
  • Passing root by value causing copy
3. Given the following binary tree and code snippet, what will be the output?
#include <iostream>
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

TreeNode* findLCA(TreeNode* root, int n1, int n2) {
  if (!root) return nullptr;
  if (root->val == n1 || root->val == n2) return root;
  TreeNode* left = findLCA(root->left, n1, n2);
  TreeNode* right = findLCA(root->right, n1, n2);
  if (left && right) return root;
  return left ? left : right;
}

int main() {
  TreeNode* root = new TreeNode(3);
  root->left = new TreeNode(5);
  root->right = new TreeNode(1);
  root->left->left = new TreeNode(6);
  root->left->right = new TreeNode(2);
  root->right->left = new TreeNode(0);
  root->right->right = new TreeNode(8);
  TreeNode* lca = findLCA(root, 6, 2);
  std::cout << lca->val << std::endl;
  return 0;
}
medium
A. 6
B. 3
C. 2
D. 5

Solution

  1. Step 1: Trace the tree structure and nodes

    Nodes 6 and 2 are both children of node 5 in the tree.
  2. Step 2: Apply LCA logic

    Since 5 is the lowest node that has both 6 and 2 as descendants, the function returns node 5.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    LCA(6,2) = 5 [OK]
Hint: LCA is ancestor closest to both nodes [OK]
Common Mistakes:
  • Choosing root 3 instead of node 5
  • Confusing child nodes as LCA
  • Returning one of the input nodes incorrectly
4. Identify the bug in the following LCA function and select the correct fix:
TreeNode* findLCA(TreeNode* root, int n1, int n2) {
  if (!root) return nullptr;
  if (root->val == n1 || root->val == n2) return root;
  TreeNode* left = findLCA(root->left, n1, n2);
  TreeNode* right = findLCA(root->right, n1, n2);
  if (left && right) return root;
  if (left) return right;
  return right;
}
medium
A. Add a check for root being nullptr after recursive calls
B. Change 'if (left && right) return root;' to 'return nullptr;'
C. Change 'if (left) return right;' to 'if (left) return left;'
D. Change return type to int instead of TreeNode*

Solution

  1. Step 1: Analyze the return statements

    The code incorrectly returns 'right' when 'left' is true, which is wrong logic.
  2. Step 2: Correct the return for left subtree

    It should return 'left' when 'left' is true and 'right' is false to propagate the found node correctly.
  3. Final Answer:

    Change 'if (left) return right;' to 'if (left) return left;' -> Option C
  4. Quick Check:

    Return correct subtree pointer [OK]
Hint: Return the non-null subtree pointer correctly [OK]
Common Mistakes:
  • Returning wrong subtree pointer
  • Ignoring nullptr checks
  • Changing return type unnecessarily
5. Given a binary tree where nodes may not contain unique values, which modification is necessary to correctly find the LCA of two nodes identified by their pointers (not values)?
hard
A. Modify the LCA function to compare node pointers directly instead of values
B. Use node values for comparison as usual, ignoring pointer identity
C. Sort the tree nodes before finding LCA to ensure uniqueness
D. Replace the binary tree with a binary search tree for unique values

Solution

  1. Step 1: Understand the problem with duplicate values

    If nodes have duplicate values, comparing values is ambiguous and can lead to wrong LCA.
  2. Step 2: Use pointer comparison

    Comparing node pointers directly ensures the exact nodes are identified regardless of value duplicates.
  3. Step 3: Modify function accordingly

    The LCA function should check if the current node pointer equals either of the target node pointers.
  4. Final Answer:

    Modify the LCA function to compare node pointers directly instead of values -> Option A
  5. Quick Check:

    Compare pointers, not values, for duplicates [OK]
Hint: Compare node addresses, not values, for duplicates [OK]
Common Mistakes:
  • Using values for comparison with duplicates
  • Assuming tree is BST to fix duplicates
  • Sorting nodes which is unnecessary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard