Skip to content

Commit 71997cc

Browse files
authored
Create check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.cpp
1 parent 5e3940e commit 71997cc

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Time: O(n)
2+
// Space: O(w)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
11+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13+
* };
14+
*/
15+
// bfs solution
16+
class Solution {
17+
public:
18+
bool isValidSequence(TreeNode* root, vector<int>& arr) {
19+
vector<TreeNode *> q = {root};
20+
for (int depth = 0; depth < arr.size(); ++depth) {
21+
vector<TreeNode *> new_q;
22+
while (!q.empty()) {
23+
const auto node = q.back(); q.pop_back();
24+
if (!node || node->val != arr[depth]) {
25+
continue;
26+
}
27+
if (depth + 1 == arr.size() && node->left == node->right) {
28+
return true;
29+
}
30+
new_q.emplace_back(node->left);
31+
new_q.emplace_back(node->right);
32+
}
33+
q = move(new_q);
34+
}
35+
return false;
36+
}
37+
};
38+
39+
// Time: O(n)
40+
// Space: O(h)
41+
// dfs solution with stack
42+
class Solution2 {
43+
public:
44+
bool isValidSequence(TreeNode* root, vector<int>& arr) {
45+
vector<pair<TreeNode *, int>> s = {{root, 0}};
46+
while (!s.empty()) {
47+
const auto [node, depth] = s.back(); s.pop_back();
48+
if (!node || depth == arr.size() || node->val != arr[depth]) {
49+
continue;
50+
}
51+
if (depth + 1 == arr.size() && node->left == node->right) {
52+
return true;
53+
}
54+
s.emplace_back(node->right, depth + 1);
55+
s.emplace_back(node->left, depth + 1);
56+
}
57+
return false;
58+
}
59+
};
60+
61+
// Time: O(n)
62+
// Space: O(h)
63+
// dfs solution with recursion
64+
class Solution3 {
65+
public:
66+
bool isValidSequence(TreeNode* root, vector<int>& arr) {
67+
return dfs(root, arr, 0);
68+
}
69+
70+
private:
71+
bool dfs(TreeNode *node, const vector<int>& arr, int depth) {
72+
if (!node || depth == arr.size() || node->val != arr[depth]) {
73+
return false;
74+
}
75+
if (depth + 1 == arr.size() && node->left == node->right) {
76+
return true;
77+
}
78+
return dfs(node->left, arr, depth + 1) || dfs(node->right, arr, depth + 1);
79+
}
80+
};

0 commit comments

Comments
 (0)