From 8958a3bcc887ddb5fabccd86de320d63108f2a8e Mon Sep 17 00:00:00 2001 From: Legion 4600H Date: Wed, 5 Oct 2022 16:55:21 +0530 Subject: [PATCH] lowestCommonAncestor.txt added --- LeetCode Solutions/lowestCommonAncestor.txt | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 LeetCode Solutions/lowestCommonAncestor.txt diff --git a/LeetCode Solutions/lowestCommonAncestor.txt b/LeetCode Solutions/lowestCommonAncestor.txt new file mode 100644 index 00000000..5917bff0 --- /dev/null +++ b/LeetCode Solutions/lowestCommonAncestor.txt @@ -0,0 +1,31 @@ +Problem Link - https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ +/** + * 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* lca(TreeNode* root,int l,int r){ + if(((l<(root->val)) and (r>(root->val))) or ((l>(root->val)) and (r<(root->val)))){ + return root; + } + else if((root->val==l) or (root->val==r)){ + return root; + } + else if(((root->val)>l) and ((root->val)>r)){ + return lca(root->left,l,r); + } + return lca(root->right,l,r); + + + } + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + return lca(root,p->val,q->val); +    } +}; \ No newline at end of file