Postorder traversal: when about to visit a node, the nodes in the stack are all nodes on the path from root to the current node. Find the two paths from root to p and q, then find the last common node of these two paths. Note that the problem states that each node value is different, so we can directly compare Rc. This comparison method compares the values pointed to by Rc. Using the Rc::ptr_eq method can compare whether two Rc are cloned from the same Rc.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution {
public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){ // Base case: if root is null, or is p or q, return directly if (!root || root == p || root == q) return root;
// Find p or q in the left subtree TreeNode* left = lowestCommonAncestor(root->left, p, q); // Find p or q in the right subtree TreeNode* right = lowestCommonAncestor(root->right, p, q);
// Case 1: Both found → current root is the lowest common ancestor if (left && right) return root;
// Case 2: Only one found → return that one upward return left ? left : right; }
TreeNode *left = lowestCommonAncestor(root->left, p, q); // Find p or q in left subtree TreeNode *right = lowestCommonAncestor(root->right, p, q); // Find p or q in right subtree
if (left && right) // If both left and right subtrees find return root;
return left == nullptr ? right : left; // Otherwise return the one found } };