1367. 二叉树中的链表
题目
传送门:https://leetcode.cn/problems/linked-list-in-binary-tree/
算法设计:深度优先搜索
遍历二叉树套遍历二叉树,在每个节点尝试是否能形成一个链表。
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if(root == nullptr) return false;
if(match(head, root)) return true;
return isSubPath(head, root->left) || isSubPath(head, root->right);
}
bool match(ListNode* head, TreeNode* root) {
if(!head) return true;
if(!root || root->val!=head->val) return false;
return match(head->next, root->left) || match(head->next, root->right);
}
};