Skip to content

1367. Linked List in Binary Tree

View on LeetCode

Approach: DFS over tree starts; from a value match, try to match the full list downward via left/right.

Complexity: O(n·m) time, O(h) space

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSubPath = function(head, root) {
    if (!root) {
        return false
    }
    if (root.val === head.val) {
        if (check(head, root)) {
            return true
        }
    }
    return isSubPath(head, root.left) || isSubPath(head, root.right)

};

function check(head, root) {
    if (!head) {
        return true
    }
    if (!root) {
        return false
    }
    if (head.val !== root.val) {
        return false
    }
    return check(head.next, root.left) || check(head.next, root.right)
}