-
Notifications
You must be signed in to change notification settings - Fork 6
/
50_LastCommonParentInTree.cpp
139 lines (124 loc) · 2.38 KB
/
50_LastCommonParentInTree.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
#define MAX 100006
bool TF = false;
struct BinaryTree
{
int value;
BinaryTree *left;
BinaryTree *right;
};
BinaryTree *CreateTree(BinaryTree **root)
{
BinaryTree *index = NULL;
int tmp;
cin >> tmp;
if (tmp == 0)
return NULL;
(*root) = new BinaryTree;
index = *root;
index->value = tmp;
index->left = NULL;
index->right = NULL;
CreateTree(&(index->left));
CreateTree(&(index->right));
return *root;
}
void DeleteTree(BinaryTree **root)
{
if ((*root) == NULL)
return ;
BinaryTree *index = *root;
DeleteTree(&(index->left));
DeleteTree(&(index->right));
delete index;
}
void PreOrderTraverse(BinaryTree *root)
{
if (root == NULL)
return;
BinaryTree *index = root;
PreOrderTraverse(index->left);
cout << index->value << " ";
PreOrderTraverse(index->right);
}
bool GetNodePath(BinaryTree *root, int value, vector<BinaryTree *> &path)
{
BinaryTree *index;
if (root == NULL)
return false;
path.push_back(root);
if (root->value == value)
return true;
bool found = GetNodePath(root->left, value, path);
if (found)
return true;
else
{
found = GetNodePath(root->right, value, path);
if (found)
return true;
else
{
path.pop_back();
return false;
}
}
}
BinaryTree *GetLastCommonNode(vector<BinaryTree *> path1, vector<BinaryTree *> path2)
{
vector<BinaryTree *>::iterator iter1 = path1.begin(), iter2 = path2.begin();
BinaryTree *last_node = 0;
if (path1.size() == 0 || path2.size() == 0)
{
TF = false;
return 0;
}
while (iter1 != path1.end() && iter2 != path2.end())
{
if (*iter1 == *iter2)
{
TF = true;
last_node = *iter1;
}
iter1 ++;
iter2 ++;
}
return last_node;
}
BinaryTree* GetLastCommonParent(BinaryTree *root, int num1, int num2)
{
if (root == NULL)
{
TF = false;
return 0;
}
vector<BinaryTree *> path1, path2;
bool TF1, TF2;
GetNodePath(root, num1, path1);
GetNodePath(root, num2, path2);
return GetLastCommonNode(path1, path2);
}
int main(void)
{
int n, num1, num2;
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
cin >> n;
while (n--)
{
BinaryTree *root = NULL;
CreateTree(&root);
scanf("%d", &num1);
scanf("%d", &num2);
BinaryTree* common_node = GetLastCommonParent(root, num1, num2);
if (TF == false)
printf("My God\n");
else
printf("%d\n", common_node->value);
DeleteTree(&root);
}
return 0;
}