jayati

Lowest Common Ancestor of a Binary Search Tree

Mar 20th, 2023
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10.  
  11. class Solution {
  12. public:
  13.     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14.         if (root == NULL || p->val == root->val || q->val == root->val)
  15.             return root;
  16.         if (p->val < root->val && q->val < root->val)
  17.                 return lowestCommonAncestor(root->left, p, q);
  18.         if (p->val > root->val && q->val > root->val)
  19.                 return lowestCommonAncestor(root->right, p, q);
  20.         return root;
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment