查看: 1412| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] 请问这道题我的接发的时间复杂度是?

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
刷题一直都没在意Time complexity和Space complexity。。。惭愧。最近开始练习分析大O,但这道题实在不会了,请问它的时间复杂度是,以及如何分析?谢谢啦!!
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.    
  12.     // The list stores all the possible nodes whose values are the same as t's value
  13.     ArrayList<TreeNode> list = new ArrayList<>();
  14.     int target;
  15.    
  16.     public boolean isSubtree(TreeNode s, TreeNode t) {
  17.         
  18.         target = t.val;
  19.         
  20.         // Depth first search s, find all the possible nodes
  21.         dfs(s);
  22.         
  23.         if(list.isEmpty())
  24.             return false;
  25.         
  26.         for(TreeNode node : list){
  27.             if(isIdentical(node, t))
  28.                 return true;
  29.         }
  30.         
  31.         return false;   
  32.     }
  33.    
  34.    
  35.     public void dfs(TreeNode s){
  36.         if(s == null)
  37.             return;
  38.         if(s.val == target)
  39.             list.add(s);
  40.         dfs(s.left);
  41.         dfs(s.right);
  42.     }
  43.    
  44.     public boolean isIdentical(TreeNode s, TreeNode t){
  45.         
  46.                 // The s and t should reach the end of the trees together
  47.         if(s == null && t == null)
  48.             return true;
  49.         if(s == null || t == null)
  50.             return false;
  51.         if(s.val != t.val)
  52.             return false;
  53.             
  54.         return isIdentical(s.left, t.left) && isIdentical(s.right, t.right);
  55.     }
  56. }
复制代码






上一篇:求问一道算法题
下一篇:我面试的都是开发,sql的题有必要刷吗?
推荐
magicsets 2019-10-11 11:27:44 | 只看该作者
全局:
设 |X| = 以 X 为树根的subtree中的节点总数

那么:

isIdentical(TreeNode s, TreeNode t)的时间复杂度 = O( min(|s|, |t|) )

dfs(TreeNode s)的时间复杂度 = O(|s|)

isSubtree(TreeNode s, TreeNode t)的时间复杂度 = dfs(TreeNode s)的时间复杂度 + |s| * isIdentical(TreeNode s, TreeNode t)的时间复杂度 = O( |s| * min(|s|, |t|) ) <= O( |s| * |t| )
回复

使用道具 举报

🔗
 楼主| chen3211 2019-10-11 08:09:23 | 只看该作者
全局:
忘记说:isSubtree(TreeNode s, TreeNode t)是主方法。题目:https://leetcode.com/problems/subtree-of-another-tree/
回复

使用道具 举报

🔗
 楼主| chen3211 2019-10-15 23:43:04 | 只看该作者
全局:
magicsets 发表于 2019-10-11 11:27
设 |X| = 以 X 为树根的subtree中的节点总数

那么:

太感谢了!!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表