-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLowest Common Ancestor of a Binary Search Tree.cpp
61 lines (55 loc) · 1.26 KB
/
Lowest Common Ancestor of a Binary Search Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
/**
* 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 || !p || !q) {
return NULL;
}
while(root) {
if(p->val < root->val && q->val < root->val) {
root = root->left;
}
else if(p->val > root->val && q->val > root->val) {
root = root->right;
}
else {
return root;
}
}
return root;
}
};
TreeNode *buildTree(int depth, int &val) {
TreeNode *root = new TreeNode(val);
if(depth == 0) {
return root;
}
root->left = buildTree(depth - 1, ++val);
root->right = buildTree(depth - 1, ++val);
return root;
}
int main() {
int val = 1;
// TreeNode *tree = buildTree(2, val);
TreeNode *tree = new TreeNode(2);
tree->left = new TreeNode(2);
tree->right = new TreeNode(3);
tree->right->left = new TreeNode(4);
tree->right->right = new TreeNode(5);
Solution s;
cout << s.maxPathSum(tree) << endl;
return 0;
}