递归法:
1.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool dfs(struct ListNode* head, struct TreeNode* root)
{
if(head==NULL) // 如果链表一直匹配到底
{
return true;
}
if(root==NULL) // 如果树已经到底
{
return false;
}
if(head->val!=root->val) // 如果当前的链表值和树节点值不等
{
return false;
}
// 剩下的就是部分匹配的情况,就检查链表的下一个节点和树节点的左右子树是否匹配
return dfs(head->next, root->left) || dfs(head->next, root->right);
}
bool isSubPath(struct ListNode* head, struct TreeNode* root){
// 递归的思想
if(root==NULL) return false;
return dfs(head,root) || isSubPath(head,root->left) || isSubPath(head,root->right);
}