-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
42 lines (39 loc) · 1.16 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
const dfs = (head: ListNode | null, root: TreeNode | null) => {
if (head == null) {
return true;
}
if (root == null || head.val !== root.val) {
return false;
}
return dfs(head.next, root.left) || dfs(head.next, root.right);
};
function isSubPath(head: ListNode | null, root: TreeNode | null): boolean {
if (root == null) {
return false;
}
return dfs(head, root) || isSubPath(head, root.left) || isSubPath(head, root.right);
}