3687 · Check If an Array Is a Valid Sequence
Algorithms
Medium
Description
Given a binary tree with a root node root, we call the sequence of node values in any path from the root node to any leaf node is a “valid sequence” of that binary tree.
Now you are given an array of integers arr as a sequence, and you need to check whether it is a “valid sequence” of the given binary tree.
A valid sequence must be from the root node to the leaf nodes
Example
Example 1
Input
root = [0,1,0,0,1,0,#,#,1,0,0]
arr = [0,1,0,1]
Output
true
Explanation
The path 0 -> 1 -> 0 -> 1 is a valid sequence.
The given binary tree is:
0
/
1 0
/ \ /
0 1 0
\ /
1 0 0
Other valid sequences are:
0 -> 1 -> 1 -> 0
0 -> 0 -> 0
Example 2
Input
root = [0,1,0,0,1,0,#,#,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,#,#,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. Because the end of the sequence is not a leaf node.
解法1: 遍历
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: Root node of a binary tree.
* @param arr: An array of integers.
* @return: If the array is a valid sequence.
*/
bool isValidSequence(TreeNode *root, vector

最低0.47元/天 解锁文章
1491

被折叠的 条评论
为什么被折叠?



