Depth First Search

PHOTO EMBED

Tue Oct 01 2024 20:04:18 GMT+0000 (Coordinated Universal Time)

Saved by @kanatov

function isSubPath(head: ListNode | null, root: TreeNode | null): boolean {
    if (!head) return true;
    if (!root) return false;
    const dfs = (head: ListNode | null, root: TreeNode | null): boolean => {
        if (!head) return true; 
        if (!root) return false;
        if (root.val === head.val)
            return dfs(head.next, root.left) || dfs(head.next, root.right);
        return false;
    };
    return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
}
content_copyCOPY