1、https://leetcode-cn.com/problems/linked-list-in-binary-tree/
class Solution {
public:
bool dfs(ListNode* head, TreeNode* root)
{
if(head == nullptr) return true;
if(root == nullptr) 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(root == nullptr) return false;
return dfs(head,root) || isSubPath(head,root->left) || isSubPath(head,root->right);
}
};
2、https://leetcode-cn.com/problems/check-subtree-lcci/
class Solution {
public:
bool checkSubTree(TreeNode* t1, TreeNode* t2) {
if(t1 == nullptr && t2 == nullptr) return true;
if(t1 == nullptr || t2 == nullptr) return false;
return dfs(t1,t2) || checkSubTree(t1->left,t2) ||checkSubTree(t1->right,t2);
}
bool dfs(TreeNode* t1, TreeNode* t2)
{
if(t2 == nullptr) return true;
if(t1 == nullptr) return false;
if(t1->val != t2->val || t1->val != t2->val) return false;
return dfs(t1->left,t2->left) && dfs(t1->right,t2->right);
}
};
1、
2、