Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
- // Base case: If root is nullptr, or root is either p or q, return root
- if (root == nullptr || root == p || root == q) {
- return root;
- }
- // Search for p and q in the left and right subtrees
- TreeNode* left = lowestCommonAncestor(root->left, p, q);
- TreeNode* right = lowestCommonAncestor(root->right, p, q);
- // If both left and right return non-nullptr, it means p and q are in different subtrees
- if (left != nullptr && right != nullptr) {
- return root;
- }
- // If either left or right is non-nullptr, return that value
- return left != nullptr ? left : right;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement