Advertisement
asdfg0998

sdf

Sep 19th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2.         // Base case: If root is nullptr, or root is either p or q, return root
  3.         if (root == nullptr || root == p || root == q) {
  4.             return root;
  5.         }
  6.  
  7.         // Search for p and q in the left and right subtrees
  8.         TreeNode* left = lowestCommonAncestor(root->left, p, q);
  9.         TreeNode* right = lowestCommonAncestor(root->right, p, q);
  10.  
  11.         // If both left and right return non-nullptr, it means p and q are in different subtrees
  12.         if (left != nullptr && right != nullptr) {
  13.             return root;
  14.         }
  15.  
  16.         // If either left or right is non-nullptr, return that value
  17.         return left != nullptr ? left : right;
  18.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement