Lowest Common Ancestor in Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how the time taken to find the lowest common ancestor changes as the tree grows.
How does the number of steps grow when the tree has more nodes?
Analyze the time complexity of the following code snippet.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
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;
}
This code finds the lowest common ancestor of two nodes in a binary tree by searching both sides recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node is visited once during the recursion.
As the tree grows, the function visits every node once to check for the target nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 recursive calls |
| 100 | About 100 recursive calls |
| 1000 | About 1000 recursive calls |
Pattern observation: The number of steps grows roughly in direct proportion to the number of nodes.
Time Complexity: O(n)
This means the time to find the ancestor grows linearly with the number of nodes in the tree.
[X] Wrong: "The function only visits part of the tree, so it runs faster than O(n)."
[OK] Correct: The function may need to check all nodes in the worst case to find both targets, so it visits every node once.
Understanding this helps you explain how recursive tree searches work and why visiting all nodes is necessary in some cases.
"What if the tree was a binary search tree and you could use node values to guide the search? How would the time complexity change?"
Practice
Solution
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).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.Final Answer:
The deepest node that is an ancestor of both nodes -> Option AQuick Check:
LCA = deepest common ancestor [OK]
- Confusing LCA with root node
- Choosing node by value instead of position
- Thinking LCA is the first visited node in traversal
Solution
Step 1: Analyze parameter types
The function should accept a pointer to the root node and two integer values representing node keys.Step 2: Analyze return type
The function returns a pointer to the TreeNode representing the LCA, so return type must be TreeNode*.Final Answer:
TreeNode* findLCA(TreeNode* root, int n1, int n2); -> Option BQuick Check:
Function signature with pointers and correct return type [OK]
- Using value instead of pointer for root
- Returning int instead of TreeNode*
- Passing root by value causing copy
#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;
}Solution
Step 1: Trace the tree structure and nodes
Nodes 6 and 2 are both children of node 5 in the tree.Step 2: Apply LCA logic
Since 5 is the lowest node that has both 6 and 2 as descendants, the function returns node 5.Final Answer:
5 -> Option DQuick Check:
LCA(6,2) = 5 [OK]
- Choosing root 3 instead of node 5
- Confusing child nodes as LCA
- Returning one of the input nodes incorrectly
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;
}Solution
Step 1: Analyze the return statements
The code incorrectly returns 'right' when 'left' is true, which is wrong logic.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.Final Answer:
Change 'if (left) return right;' to 'if (left) return left;' -> Option CQuick Check:
Return correct subtree pointer [OK]
- Returning wrong subtree pointer
- Ignoring nullptr checks
- Changing return type unnecessarily
Solution
Step 1: Understand the problem with duplicate values
If nodes have duplicate values, comparing values is ambiguous and can lead to wrong LCA.Step 2: Use pointer comparison
Comparing node pointers directly ensures the exact nodes are identified regardless of value duplicates.Step 3: Modify function accordingly
The LCA function should check if the current node pointer equals either of the target node pointers.Final Answer:
Modify the LCA function to compare node pointers directly instead of values -> Option AQuick Check:
Compare pointers, not values, for duplicates [OK]
- Using values for comparison with duplicates
- Assuming tree is BST to fix duplicates
- Sorting nodes which is unnecessary
Ready to prove it?
Pass the test and this pattern moves unknown
