lowest-common-ancestor-of-a-binary-search-tree 1.0.0
Lowest Common Ancestor of a Binary Search Tree
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
8struct TreeNode
9{
10 int val;
13 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
14};
15
16 class Solution
17{
18public:
20 {
21 queue<TreeNode*> process_queue;
22 process_queue.push(root);
23 while (!process_queue.empty())
24 {
25 TreeNode* node = process_queue.front();
26 process_queue.pop();
27
28 if (node == p || node == q)
29 return node;
30
31 int a1 = min(p->val, q->val);
32 int a2 = max(p->val, q->val);
33
34 if (node->val > a1 && node->val < a2)
35 return node;
36
37 if (node->left)
38 process_queue.push(node->left);
39 if (node->right)
40 process_queue.push(node->right);
41 }
42 return NULL;
43 }
44};
45
46int main()
47{
48 unique_ptr<TreeNode> root(make_unique<TreeNode>(6));
49 unique_ptr<TreeNode> p(make_unique<TreeNode>(2));
50 unique_ptr<TreeNode> q(make_unique<TreeNode>(8));
51 root->left = p.get();
52 root->right = q.get();
53 cout << "output: " << Solution().lowestCommonAncestor(root.get(), p.get(), q.get())->val << '\n';
54 return 0;
55}
TreeNode * lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
Definition main.cpp:19
int main()
Definition main.cpp:46
Definition for a binary tree node.
Definition main.cpp:9
int val
Definition main.cpp:10
TreeNode * left
Definition main.cpp:11
TreeNode * right
Definition main.cpp:12
TreeNode(int x)
Definition main.cpp:13