LintCode 3687 · Check If an Array Is a Valid Sequence (二叉树遍历和分治好题)

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<int> &arr) {
        if (!root) return arr.size() == 0;
        helper(root, arr, 0);
        return found;
    }
private:
    bool found = false;
    void helper(TreeNode *root, vector<int> &arr, int start) {
        if (found || !root || root->val != arr[start]) return;
        if (!root->left && !root->right && root->val == arr[start] && start == arr.size() - 1) {
            found = true;
            return;
        }
        start++;
        helper(root->left, arr, start);
        helper(root->right, arr, start);
        start--;
    }
};

解法2:分治
注意:分治的解法里面,index加1后不用再减回去。但是如果是回溯的话,加了之后要减回去。参考上面的start–。


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<int> &arr) {
        return helper(root, arr, 0);
    }
private:
    bool helper(TreeNode *root, vector<int> &arr, int index) {
        if (!root) return arr.empty();
        if (root->val != arr[index]) return false;
        if (!root->left && !root->right && root->val == arr.back()) return true;
        return helper(root->left, arr, index + 1) || helper(root->right, arr, index + 1);
    }
};

你可能感兴趣的:(leetcode,算法)