如果直接这样写去搜搜,那么会超时,因为存在大量回溯过程
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if(head == nullptr) {
return true;
}
if(root == nullptr) {
return false;
}
if(head->val == root->val && (isSubPath(head->next, root->left) || isSubPath(head->next, root->right))) {
return true;
}
if(isSubPath(head, root->left) || isSubPath(head, root->right)) {
return true;
}
return false;
}
};
优化的方法是将函数拆分成两个函数,一个判断从当前节点出发,一个遍历所有节点
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if(root == nullptr) return false;
return helper(head, root) || isSubPath(head, root->left) || isSubPath(head, root->right);
}
bool helper(ListNode* head, TreeNode* root) {
if(head == nullptr) {
return true;
}
if(root == nullptr || root->val != head->val) {
return false;
}
return helper(head->next, root->left) || helper(head->next, root->right);
}
};