[LeetCode] Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.

We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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) {}
* };
*/
class Solution {
bool helper(TreeNode* node, vector<int>& A, int pos) {
if(pos == A.size() or node == nullptr or node->val != A[pos]) return false;
if(pos == A.size() - 1 and node->left == nullptr and node->right == nullptr) return true;
return helper(node->left, A, pos + 1) or helper(node->right, A, pos + 1);
}
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
return helper(root, arr, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/22/PS/LeetCode/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.