[AlgoExpert] Validate Three Nodes

Validate Three Nodes

  • Time : O(n)
  • Space : O(n)
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
using namespace std;

// This is an input class. Do not edit.
class BST {
public:
int value;
BST *left = nullptr;
BST *right = nullptr;

BST(int value) { this->value = value; }
};

void verifyNodeIsOneOrThree(BST* node, BST* nodeOne, BST* nodeThree, bool& one, bool& three) {
if(node == nodeOne) {
one = true;
}
if(node == nodeThree) {
three = true;
}
}


bool validateThreeNodes(BST *nodeOne, BST *nodeTwo, BST *nodeThree) {
bool one = false, three = false;
queue<BST*> q;
q.push(nodeTwo);

while(!q.empty()) {
auto node = q.front(); q.pop();
if(node->left) {
verifyNodeIsOneOrThree(node->left, nodeOne, nodeThree, one, three);
q.push(node->left);
}
if(node->right) {
verifyNodeIsOneOrThree(node->right, nodeOne, nodeThree, one, three);
q.push(node->right);
}
}

if(one == three) return false;

if(one) q.push(nodeThree);
else q.push(nodeOne);

while(!q.empty()) {
auto node = q.front(); q.pop();
if(node->left) {
if(node->left == nodeTwo)
return true;
q.push(node->left);
}
if(node->right) {
if(node->right == nodeTwo)
return true;
q.push(node->right);
}
}

return false;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/validate-three-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.