Skip to content

Commit

Permalink
lowestCommonAncestor.txt added
Browse files Browse the repository at this point in the history
  • Loading branch information
kokodeshinu committed Oct 5, 2022
1 parent fec7629 commit 8958a3b
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions LeetCode Solutions/lowestCommonAncestor.txt
Original file line number Diff line number Diff line change
@@ -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);
    }
};

0 comments on commit 8958a3b

Please sign in to comment.