Leetcode 1484 Solution

This article provides solution to leetcode question 1484 (linked-list-in-binary-tree)

https://leetcode.com/problems/linked-list-in-binary-tree

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 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 isSubPath(self, head: ListNode, root: TreeNode) -> bool:
        def validate(tree_node, list_node):
            if list_node is None:
                return True

            if tree_node is None:
                return False

            if tree_node.val != list_node.val:
                return False

            return validate(tree_node.left, list_node.next) or validate(tree_node.right, list_node.next)

        def validate_all_nodes(tree_node):
            nonlocal head

            if validate(tree_node, head):
                return True

            if tree_node is None:
                return False

            return validate_all_nodes(tree_node.left) or validate_all_nodes(tree_node.right)

        return validate_all_nodes(root)