From 40bd17d6423c0a14a445a67abf00e235bf958b92 Mon Sep 17 00:00:00 2001 From: Akshat verma <99114167+akshatvermavi@users.noreply.github.com> Date: Mon, 26 Jun 2023 23:21:03 +0530 Subject: [PATCH] Create Leetcode_medium_235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree --- ...ommon_Ancestor_of_a_Binary_Search_Tree.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Leetcode_medium_235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp diff --git a/Leetcode_medium_235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp b/Leetcode_medium_235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp new file mode 100644 index 0000000..edfcf0c --- /dev/null +++ b/Leetcode_medium_235_Lowest_Common_Ancestor_of_a_Binary_Search_Tree.cpp @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if(root ==NULL) + return NULL; + //case 1 + if(p->val val && q->val < root->val) + return lowestCommonAncestor(root->left, p, q); + //case 2 + if(p->val >root->val && q->val > root->val) + return lowestCommonAncestor(root->right, p, q); + //case 3,4 + return root; + } +};