forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.cpp
80 lines (76 loc) · 2.32 KB
/
check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.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
// Time: O(n)
// Space: O(w)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// bfs solution
class Solution {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
vector<TreeNode *> q = {root};
for (int depth = 0; depth < arr.size(); ++depth) {
vector<TreeNode *> new_q;
while (!q.empty()) {
const auto node = q.back(); q.pop_back();
if (!node || node->val != arr[depth]) {
continue;
}
if (depth + 1 == arr.size() && node->left == node->right) {
return true;
}
new_q.emplace_back(node->left);
new_q.emplace_back(node->right);
}
q = move(new_q);
}
return false;
}
};
// Time: O(n)
// Space: O(h)
// dfs solution with stack
class Solution2 {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
vector<pair<TreeNode *, int>> s = {{root, 0}};
while (!s.empty()) {
const auto [node, depth] = s.back(); s.pop_back();
if (!node || depth == arr.size() || node->val != arr[depth]) {
continue;
}
if (depth + 1 == arr.size() && node->left == node->right) {
return true;
}
s.emplace_back(node->right, depth + 1);
s.emplace_back(node->left, depth + 1);
}
return false;
}
};
// Time: O(n)
// Space: O(h)
// dfs solution with recursion
class Solution3 {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
return dfs(root, arr, 0);
}
private:
bool dfs(TreeNode *node, const vector<int>& arr, int depth) {
if (!node || depth == arr.size() || node->val != arr[depth]) {
return false;
}
if (depth + 1 == arr.size() && node->left == node->right) {
return true;
}
return dfs(node->left, arr, depth + 1) || dfs(node->right, arr, depth + 1);
}
};