Skip to content

Commit 2fa5161

Browse files
authored
Create 1367-linked-list-in-binary-tree.js
1 parent 4b55359 commit 2fa5161

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

1367-linked-list-in-binary-tree.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val, left, right) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.left = (left===undefined ? null : left)
13+
* this.right = (right===undefined ? null : right)
14+
* }
15+
*/
16+
/**
17+
* @param {ListNode} head
18+
* @param {TreeNode} root
19+
* @return {boolean}
20+
*/
21+
const isSubPath = function(head, root) {
22+
const res = { found: false }
23+
traverse(root, head, res)
24+
return res.found
25+
};
26+
27+
function traverse(node, list, res) {
28+
if(res.found) return
29+
if(node == null) return
30+
if(node.val === list.val && helper(node, list)) {
31+
res.found = true
32+
return
33+
}
34+
traverse(node.left, list, res)
35+
traverse(node.right, list, res)
36+
}
37+
38+
function helper(node, list) {
39+
if(list == null) return true
40+
if(node == null) return false
41+
if(list.val !== node.val) return false
42+
return helper(node.left, list.next) || helper(node.right, list.next)
43+
}

0 commit comments

Comments
 (0)