LeetCode 1367. 【双递归】二叉树中的列表
原题链接
中等
作者:
大明湖的鱼
,
2021-01-30 21:53:32
,
所有人可见
,
阅读 450
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool dfs(ListNode* head,TreeNode* root){
if(!head) return true;
if(!root) return false;
if(root->val != head->val) return false;
return dfs(head->next,root->left) || dfs(head->next,root->right);
}
bool isSubPath(ListNode* head, TreeNode* root) {
if(!head) return true;
if(!root) return false;
if(dfs(head,root)) return true;
return isSubPath(head,root->left) || isSubPath(head,root->right);
//决定从哪个点开始匹配
}
};