{x}
blog image

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

Solution Explanation

This problem asks whether a given integer array arr represents a valid path from the root to a leaf node in a binary tree. A valid path means that the values in arr sequentially match the node values along a path from the root to a leaf (a node with no children).

The most efficient approach is Depth-First Search (DFS). We recursively traverse the tree, checking if the current node's value matches the next element in arr.

Algorithm

  1. Base Cases:

    • If the current node is null or its value doesn't match the current element in arr, the path is invalid, so return false.
    • If we've reached the end of arr (meaning we've processed all elements), we check if the current node is a leaf node (no left or right children). If it is, the path is valid, and we return true. Otherwise, the path is invalid (we reached the end of arr before reaching a leaf), and we return false.
  2. Recursive Step:

    • Otherwise, we recursively call the dfs function on the left and right children of the current node, incrementing the index u in arr to move to the next element. We use the logical OR (|| or or) because a valid path exists if it exists in either the left or the right subtree.

Time and Space Complexity Analysis

  • Time Complexity: O(N), where N is the number of nodes in the binary tree. In the worst-case scenario, we might traverse all nodes in the tree.

  • Space Complexity: O(H), where H is the height of the binary tree. This is due to the recursive calls on the call stack. In the worst case, the height can be equal to N (for a skewed tree), but in a balanced tree, H is log₂(N).

Code Implementation (Python)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
        def dfs(root, u):
            if root is None or root.val != arr[u]:
                return False
            if u == len(arr) - 1:
                return root.left is None and root.right is None
            return dfs(root.left, u + 1) or dfs(root.right, u + 1)
 
        return dfs(root, 0)

The other languages (Java, C++, Go) follow a very similar structure to the Python code, adapting syntax and data structures as needed for each language. The core algorithm remains the same efficient DFS approach.