|
| 1 | +/** |
| 2 | + * 1367. Linked List in Binary Tree |
| 3 | + * https://leetcode.com/problems/linked-list-in-binary-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a binary tree root and a linked list with head as the first node. |
| 7 | + * |
| 8 | + * Return True if all the elements in the linked list starting from the head correspond to some |
| 9 | + * downward path connected in the binary tree otherwise return False. |
| 10 | + * |
| 11 | + * In this context downward path means a path that starts at some node and goes downwards. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * Definition for singly-linked list. |
| 16 | + * function ListNode(val, next) { |
| 17 | + * this.val = (val===undefined ? 0 : val) |
| 18 | + * this.next = (next===undefined ? null : next) |
| 19 | + * } |
| 20 | + */ |
| 21 | +/** |
| 22 | + * Definition for a binary tree node. |
| 23 | + * function TreeNode(val, left, right) { |
| 24 | + * this.val = (val===undefined ? 0 : val) |
| 25 | + * this.left = (left===undefined ? null : left) |
| 26 | + * this.right = (right===undefined ? null : right) |
| 27 | + * } |
| 28 | + */ |
| 29 | +/** |
| 30 | + * @param {ListNode} head |
| 31 | + * @param {TreeNode} root |
| 32 | + * @return {boolean} |
| 33 | + */ |
| 34 | +var isSubPath = function(head, root) { |
| 35 | + if (!head) return true; |
| 36 | + if (!root) return false; |
| 37 | + return checkPath(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right); |
| 38 | + |
| 39 | + function checkPath(listNode, treeNode) { |
| 40 | + if (!listNode) return true; |
| 41 | + if (!treeNode) return false; |
| 42 | + if (listNode.val !== treeNode.val) return false; |
| 43 | + return checkPath(listNode.next, treeNode.left) || checkPath(listNode.next, treeNode.right); |
| 44 | + } |
| 45 | +}; |
0 commit comments