题目地址:
https://leetcode.com/problems/linked-list-in-binary-tree/
给定一棵二叉树和一个链表,问二叉树中是否存在从上到下的一条链,使得这条链上的数字刚好和链表的数一一对应。
思路是DFS + 哈希。枚举二叉树中的每个节点,看以当前点为终点且长度与链表长度相等的路径是否与链表的值一一对应,这可以用Rabin-Karp或者字符串哈希的思想来做。代码如下:
class Solution {
public:
using ULL = unsigned long long;
ULL P = 131, hash = 0, pow = 1;
int n = 0;
bool isSubPath(ListNode* head, TreeNode* root) {
while (head) {
hash = hash * P + head->val;
pow *= P;
n++;
head = head->next;
}
vector<int> v;
return dfs(root, 0, v);
}
bool dfs(TreeNode* cur, ULL h, vector<int> &v) {
if (!cur) return false;
h = h * P + cur->val;
if (v.size() >= n) h -= v[v.size() - n] * pow;
if (h == hash) return true;
v.push_back(cur->val);
if (dfs(cur->left, h, v) || dfs(cur->right, h, v)) return true;
v.pop_back();
return false;
}
};
时间复杂度 O ( n + l ) O(n+l) O(n+l), n n n是二叉树节点数, l l l是链表长度,空间 O ( h ) O(h) O(h)。