We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2cfe89c commit d8935e5Copy full SHA for d8935e5
18 - Binary Search Tree Data Structure Problems/10 - Lowest Common Ancestor of a Binary Search Tree/main.cpp
@@ -0,0 +1,26 @@
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) return NULL;
15
16
+ if(root -> val < p -> val && root -> val < q -> val) {
17
+ return lowestCommonAncestor(root -> right, p, q);
18
+ }
19
20
+ if(root -> val > p -> val && root -> val > q -> val){
21
+ return lowestCommonAncestor(root -> left, p, q);
22
23
24
+ return root;
25
26
+};
0 commit comments