LeetCode 1430: Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree Solution
Master LeetCode problem 1430 (Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree
Problem Explanation
Explanation
To solve this problem, we can perform a depth-first traversal of the binary tree while keeping track of the current index of the string we are checking. At each node, we check if the current index matches the value at the node. If it does, we recursively check the left and right subtrees with the next index. If we reach a leaf node and the index matches the length of the string, we return true, indicating that the string is a valid sequence from the root to that leaf.
Algorithm:
- Perform a depth-first traversal of the binary tree.
- At each node, check if the current index matches the value at the node.
- If it does, recursively check the left and right subtrees with the next index.
- If we reach a leaf node and the index matches the length of the string, return true.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree.
Space Complexity:
The space complexity of this algorithm is O(h), where h is the height of the binary tree.
Solution Code
class Solution {
public boolean isValidSequence(TreeNode root, int[] arr) {
return isValid(root, arr, 0);
}
private boolean isValid(TreeNode node, int[] arr, int index) {
if (node == null || index >= arr.length || node.val != arr[index]) {
return false;
}
if (node.left == null && node.right == null && index == arr.length - 1) {
return true;
}
return isValid(node.left, arr, index + 1) || isValid(node.right, arr, index + 1);
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1430 (Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree)?
This page provides optimized solutions for LeetCode problem 1430 (Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1430 (Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree)?
The time complexity for LeetCode 1430 (Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1430 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1430 in Java, C++, or Python.