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 integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

    Example 1:

    回溯法求解Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree - 图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:

    回溯法求解Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree - 图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:

    回溯法求解Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree - 图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.


    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. bool isValidSequence(TreeNode* root, vector<int>& arr) {
    15. int size = arr.size();
    16. if(root == NULL && size == 0)
    17. return true;
    18. if(root == NULL)
    19. return false;
    20. if(size == 0)
    21. return false;
    22. if(root->val != arr[0])
    23. return false;
    24. vector<int>next(arr.begin() + 1, arr.end());
    25. if(next.size() == 0)
    26. {
    27. if(root->left == NULL & root->right == NULL)
    28. return true;
    29. else
    30. return false;
    31. }
    32. if(isValidSequence(root->left, next))
    33. return true;
    34. if(isValidSequence(root->right, next))
    35. return true;
    36. return false;
    37. }
    38. };