Skip to main content
Back to problems
#1430
Medium Algorithms

Check if a string is a valid sequence from root to leaves path in a binary tree

Tree Depth-First Search Breadth-First Search Binary Tree
47.5% acceptance
Mar 31, 2026
219
15

No description available.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;

impl Solution {
  pub fn is_valid_sequence(root: Option<Rc<RefCell<TreeNode>>>, arr: Vec<i32>) -> bool {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, arr: &[i32], idx: usize) -> bool {
      match node {
        None => false,
        Some(n) => {
          let n = n.borrow();
          if idx >= arr.len() || n.val != arr[idx] {
            return false;
          }
          if idx == arr.len() - 1 {
            return n.left.is_none() && n.right.is_none();
          }
          dfs(&n.left, arr, idx + 1) || dfs(&n.right, arr, idx + 1)
        }
      }
    }
    dfs(&root, &arr, 0)
  }
}