# 【LeetCode】 Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree ## Description > 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. > Constraints: > * `1 <= arr.length <= 5000` > * `0 <= arr[i] <= 9` > * Each node's value is between [0 - 9]. > 給予一個二元樹,每個從樹根到樹葉的路徑都可以組成一段合法序列,檢查給予的字串是否和任意路徑的合法序列相同。 > 我們從整數陣列`arr`中得到給定的字串,且我們可以在二元樹中每個節點中的值組合起來得到一段序列。 > 限制: > * `1 <= arr.length <= 5000` > * `0 <= arr[i] <= 9` > * 每個節點中的值介於 [0 - 9]. ## Example: ``` 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. ``` ![](https://i.imgur.com/P4iwUM1.png) ![](https://i.imgur.com/gEg87dK.png) ![](https://i.imgur.com/iH9Rkj9.png) ## Solution * 用DFS去跑每個路徑查看是否吻合即可。 * 成功條件: * `arr`已經都配對完畢,且節點是樹葉。 * 剪枝條件: * `arr`已經都配對完畢,但節點不是樹葉。 * 節點和`arr`不吻合。 * 節點不存在(`NULL`) ### Code ```C++=1 /** * 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) { if(!root) return false; if(root->val == arr[0]) { if(arr.size() == 1) { if(!root->left && !root->right) return true; return false; } vector<int> sub_arr(arr.begin() + 1, arr.end()); return isValidSequence(root->left, sub_arr) || isValidSequence(root->right, sub_arr); } return false; } }; ``` ###### tags: `LeetCode` `C++`