-
Notifications
You must be signed in to change notification settings - Fork 14
/
BST_lowest_common_ancestor.cpp
43 lines (37 loc) · 1.4 KB
/
BST_lowest_common_ancestor.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
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <cassert>
#include <memory>
#include "./BST_prototype.h"
using std::unique_ptr;
// @include
BSTNode<int>* find_LCA(const unique_ptr<BSTNode<int>>& x,
const unique_ptr<BSTNode<int>>& s,
const unique_ptr<BSTNode<int>>& b) {
auto* p = x.get();
while (p->data < s->data || p->data > b->data) {
while (p->data < s->data) {
p = p->right.get(); // LCA must be in p's right child.
}
while (p->data > b->data) {
p = p->left.get(); // LCA must be in p's left child.
}
}
// p->data >= s->data && p->data <= b->data.
return p;
}
// @exclude
int main(int argc, char* argv[]) {
// 3
// 2 5
// 1 4 6
unique_ptr<BSTNode<int>> root = unique_ptr<BSTNode<int>>(new BSTNode<int>{3});
root->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{2});
root->left->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{1});
root->right = unique_ptr<BSTNode<int>>(new BSTNode<int>{5});
root->right->left = unique_ptr<BSTNode<int>>(new BSTNode<int>{4});
root->right->right = unique_ptr<BSTNode<int>>(new BSTNode<int>{6});
assert(3 == find_LCA(root, root->left->left, root->right->left)->data);
assert(5 == find_LCA(root, root->right->left, root->right->right)->data);
assert(2 == find_LCA(root, root->left->left, root->left)->data);
return 0;
}