题目描述:
题解:一开始处理的时候写了个dfs一直超时,其实先用bfs找到所有可能的起始点,对每个起始点dfs一下就可以了。
(纯dfs的话,如果树很深的时候,会一直先尝试一个分支到低端,很容易就超时了)
AC代码:
class Solution { public: int dfs(ListNode* head,TreeNode* root) { if(head == NULL) return 1; if(head != NULL && root==NULL) return -1; // cout << head->val <<" " << root->val <<endl; if(head->val != root->val) return -1; if(dfs(head->next,root->right) == 1) return 1; if(dfs(head->next,root->left) == 1) return 1; return -1; } bool isSubPath(ListNode* head, TreeNode* root) { queue<TreeNode*> que; que.push(root); if(head == NULL) return true; if(head != NULL && root == NULL) return false; while(que.size()) { TreeNode* now = que.front(); que.pop(); if(now->val == head->val) { if(dfs(head,now) == 1) return true; } if(now->left != NULL) que.push(now->left); if(now->right != NULL) que.push(now->right); } return false; } };