-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommonAncestorsOfNodes_inBST.cpp
108 lines (90 loc) · 1.94 KB
/
CommonAncestorsOfNodes_inBST.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
////----------------------Checking the common ancestors of two nodes
////------------------------------------
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class TreeNode
{
int Data;
TreeNode* Left;
TreeNode* Right;
friend class BST;
};
class BST
{
private:
TreeNode* Root;
void insertRecursive(TreeNode*& currNode, TreeNode* newNode)
{
if (currNode == nullptr)
currNode = newNode;
else if (newNode->Data < currNode->Data)
insertRecursive(currNode->Left, newNode);
else
insertRecursive(currNode->Right, newNode);
}
void Ancestor(int Value, vector<TreeNode*>& Ancestors, TreeNode* CurrNode)
{
if (Value == CurrNode->Data)
return;
else if (Value < CurrNode->Data)
{
Ancestors.push_back(CurrNode);
Ancestor(Value, Ancestors, CurrNode->Left);
}
else if (Value > CurrNode->Data)
{
Ancestors.push_back(CurrNode);
Ancestor(Value, Ancestors, CurrNode->Right);
}
}
public:
BST()
{
Root = nullptr;
}
void Insert(int Value)
{
TreeNode* newNode = new TreeNode;
newNode->Data = Value;
newNode->Left = newNode->Right = nullptr;
insertRecursive(Root, newNode);
}
void commonAncestor(int X, int Y)
{
vector<TreeNode*> X_Ancestors;
vector<TreeNode*> Y_Ancestors;
Ancestor(X, X_Ancestors, Root);
Ancestor(Y, Y_Ancestors, Root);
int size = min(X_Ancestors.size(), Y_Ancestors.size());
stack<TreeNode*> S;
for (int i = 0; i < size; i++)
{
if (X_Ancestors[i]->Data == Y_Ancestors[i]->Data)
S.push(X_Ancestors[i]);
}
size = S.size();
for (int i = 1; i <= size; i++)
{
TreeNode* Value = S.top();
cout << Value->Data << " ";
S.pop();
}
}
};
int main()
{
BST b1;
b1.Insert(49);
b1.Insert(39);
b1.Insert(67);
b1.Insert(29);
b1.Insert(42);
b1.Insert(59);
b1.Insert(95);
b1.Insert(40);
b1.Insert(62);
b1.commonAncestor(29, 40);
return 0;
}