Skip to content
On this page

1367. Linked List in Binary Tree

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

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)
}