Skip to content

Commit a90b983

Browse files
committed
Time: 28 ms (34.1%), Space: 30.7 MB (87.87%) - LeetHub
1 parent 9fd4089 commit a90b983

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
/**
12+
* Definition for a binary tree node.
13+
* struct TreeNode {
14+
* int val;
15+
* TreeNode *left;
16+
* TreeNode *right;
17+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
18+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
19+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
20+
* };
21+
*/
22+
class Solution {
23+
public:
24+
bool isSubPath(ListNode* head, TreeNode* root) {
25+
if (!root) return false;
26+
return dfs(root, head) || isSubPath(head, root->left) || isSubPath(head, root->right);
27+
}
28+
29+
bool dfs(TreeNode* root, ListNode* head) {
30+
if (!head) return true;
31+
if (!root) return false;
32+
if (root->val != head->val) return false;
33+
34+
return dfs(root->left, head->next) || dfs(root->right, head->next);
35+
}
36+
};

0 commit comments

Comments
 (0)