【Leetcode】1367. Linked List in Binary Tree

题目地址:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值