forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1430.cpp
More file actions
executable file
·26 lines (23 loc) · 736 Bytes
/
LC1430.cpp
File metadata and controls
executable file
·26 lines (23 loc) · 736 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/
Time: O(n)
Space: O(h)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
return isValidSequence(0, root, arr);
}
bool is_leaf(TreeNode* root) {
return root && !root->left && !root->right;
}
bool isValidSequence(int ptr, TreeNode* root, vector<int>& arr) {
if (!root || ptr == arr.size() || root->val != arr[ptr])
return false;
else if (ptr + 1 == arr.size())
return is_leaf(root);
else
return isValidSequence(ptr + 1, root->left, arr) || isValidSequence(ptr + 1, root->right, arr);
}
};