Leetcode三十天挑战的最后一道题,果然越往后leetcode越加大难度,先是出Hard级别的题目,又是出新的题目。果然对我这种小白是够挑战的。还好今天的题我通过回溯法解决了,在官方的提示中,它提示是采用DFS,但是如果采用DFS我就需要额外为每个点建立标记,所以想了想还是用回溯法,风险就是,有可能超时,但好处是答案清晰明了。
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 integersarr
and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.Example 1:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation:
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure).
Other valid sequences are:
0 -> 1 -> 1 -> 0
0 -> 0 -> 0
Example 2:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.
Example 3:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.
Constraints:
1 <= arr.length <= 5000
0 <= arr[i] <= 9
- Each node’s value is between [0 - 9].
Hint1 Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers.
Hint2 When reaching at final position check if it is a leaf node.
/**
* 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 {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
int size = arr.size();
if(root == NULL && size == 0)
return true;
if(root == NULL)
return false;
if(size == 0)
return false;
if(root->val != arr[0])
return false;
vector<int>next(arr.begin() + 1, arr.end());
if(next.size() == 0)
{
if(root->left == NULL & root->right == NULL)
return true;
else
return false;
}
if(isValidSequence(root->left, next))
return true;
if(isValidSequence(root->right, next))
return true;
return false;
}
};