1. Root-to-Node Path Comparison
Intuition
Find root-to-node path vectors for both p and q. Compare paths index-by-index: the last node where path1[i] == path2[i] is the LCA.
When to apply: Basic baseline check.
Algorithm
- Step 1: Helper getPath(root, target, path).
- Step 2: Collect pathP and pathQ from root.
- Step 3: Loop i while pathP[i] == pathQ[i].
- Step 4: Return pathP[i - 1].
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { bool getPath(TreeNode* root, TreeNode* target, vector<TreeNode*>& path) { if (!root) return false; path.push_back(root); if (root == target) return true; if (getPath(root->left, target, path) || getPath(root->right, target, path)) return true; path.pop_back(); return false; }public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode*> pathP, pathQ; getPath(root, p, pathP); getPath(root, q, pathQ); int i = 0; while (i < pathP.size() && i < pathQ.size() && pathP[i] == pathQ[i]) i++; return pathP[i - 1]; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Two path searches taking O(n) each; comparison takes O(h). - Space complexity:
O(h)— Two path arrays storing up to h nodes.