-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1367.Linked-List-in-Binary-Tree.java
49 lines (44 loc) · 1.17 KB
/
1367.Linked-List-in-Binary-Tree.java
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
43
44
45
46
47
48
49
// https://leetcode.com/problems/linked-list-in-binary-tree/
// algorithms
// Medium (38.32%)
// Total Accepted: 5,448
// Total Submissions: 14,217
// beats 100.0% of java submissions
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
class Solution {
public boolean isSubPath(ListNode head, TreeNode root) {
if (head == null) {
return true;
}
if (root == null) {
return false;
}
if (recursive(head, root)) {
return true;
}
return isSubPath(head, root.left) || isSubPath(head, root.right);
}
private boolean recursive(ListNode head, TreeNode root) {
if (head == null) {
return true;
}
if (root == null) {
return false;
}
if (head.val != root.val) {
return false;
}
return recursive(head.next, root.left) || recursive(head.next, root.right);
}
}