← Home

Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
LC

This is one of those problems where the clean idea matters more than the amount of code. For Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, backtracking.

The notes already sitting in the source point us in the right direction:

  • backtracking

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isValidSequence.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//backtracking
02//Runtime: 92 ms
03//Memory Usage: 49 MB
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15enum class COMP_RES{
16    SAME,
17    //used when path is not complete but path is equal to former path of arr
18    NOT_DIFF,
19    DIFF
20};
21
22class Solution {
23public:
24    vector<int> arr;
25    
26    COMP_RES isValid(vector<int>& path){
27        //check if path equals to path
28        //this can be used by incomplete path
29        if(path.size() > arr.size()) return COMP_RES::DIFF;
30        for(int i = 0; i < path.size(); i++){
31            if(arr[i] != path[i]) return COMP_RES::DIFF;
32        }
33        //return NOT_DIFF when path is equal to former part of arr
34        return (path.size() == arr.size()) ? COMP_RES::SAME : COMP_RES::NOT_DIFF;
35    }
36    
37    COMP_RES backtrack(TreeNode* node, vector<int>& path){
38        if(!node->left && !node->right){
39            //leaf node
40            return isValid(path);
41        }else if(path.size() >= arr.size()){
42            //early stopping
43            return COMP_RES::DIFF;
44        }
45        
46        COMP_RES res = isValid(path);
47        if(res == COMP_RES::DIFF || res == COMP_RES::SAME) return res;
48        //now res is COMP_RES::NOT_DIFF
49        //if former part of path is equal to that of arr
50        //continue to search and append path
51        res = COMP_RES::DIFF;
52        if(node->left){
53            path.push_back(node->left->val);
54            res = backtrack(node->left, path);
55            if(res == COMP_RES::SAME) return COMP_RES::SAME;
56            path.pop_back();
57        }
58        if(node->right){
59            path.push_back(node->right->val);
60            res = backtrack(node->right, path);
61            if(res == COMP_RES::SAME) return COMP_RES::SAME;
62            path.pop_back();
63        }
64        
65        //neither of its children match arr
66        return COMP_RES::DIFF;
67    };
68    
69    bool isValidSequence(TreeNode* root, vector<int>& arr) {
70        if(!root) return false;
71        this->arr = arr;
72        vector<int> path = {root->val};
73        return backtrack(root, path) == COMP_RES::SAME;
74    }
75};
76
77//recursive
78//https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/532/week-5/3315/discuss/604349/CPP-SIMPLE-EASY-DFS-SOLUTION-WITH-COMMENTS
79//Runtime: 96 ms
80//Memory Usage: 48.9 MB
81/**
82 * Definition for a binary tree node.
83 * struct TreeNode {
84 *     int val;
85 *     TreeNode *left;
86 *     TreeNode *right;
87 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
88 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
89 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
90 * };
91 */
92class Solution {
93public:
94    bool isValidSequence(TreeNode* root, vector<int>& arr, int i = 0) {
95        if(i <= arr.size() && !root){
96            return false;
97        }
98        //stop when i is equal to arr.size()-1
99        if(i == arr.size()-1){
100            //check if its leaf
101            return root->val == arr[i] && !root->left && !root->right;
102        }
103        //continue to increase i
104        return root->val == arr[i] && (isValidSequence(root->left, arr, i+1) || isValidSequence(root->right, arr, i+1));
105    }
106};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.