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

[树/链表/图] 国内某大厂笔试

全局:

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

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

x
给一颗二叉树(不一定是complete或balanced),要求从任意一个叶子节点往上remove,直到remove完根节点,求剩下的树的个数的最大值,输入:第一行表示有多少个节点n, 第1~n-1行表示(u,v)在树中u指向v。例子:
7
1 2
1 3
2 4
2 5
3 6
3 7

删除4的叶节点之后剩下:


这样一共还有两个树,所以返回2(同时这也是最多的树的数量)

我当时只想出了硬做的办法:建图用union find最后找remove(remove就是把根设置成-1)过后的根不为-1的数量,之后再recover这棵树,但是显然这么做复杂度很差,相信有更好的做法。

求大佬给点思路


评分

参与人数 1大米 +12 收起 理由
14417335 + 12

查看全部评分


上一篇:面试中碰到LRU用Python写能用OrderedDict吗
下一篇:请问大家一般leetcode的Contest Rating都是多少?
全局:
找到某个有sibling总数最多的path

补充内容 (2020-9-4 23:27):
剩下的树的个数就是sibling的个数

评分

参与人数 1大米 +2 收起 理由
陈家洛 + 2 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
mc2 2020-9-4 23:48:23 | 只看该作者
全局:
  1. public int getMaxIslandsAfterDeletion(TreeNode root) {
  2.     return dfs(root, 0);
  3.   }

  4.   // otherIslandsLeft means if node were deleted, how many other islands above node will survive
  5.   public int dfs(TreeNode node, int otherIslandsLeft) {
  6.     int best = otherIslandsLeft;
  7.     // because both node exist, therefore no matter which child is deleted (by definition, I will
  8.     // also be removed), the other child node will survive
  9.     if (node.left != null && node.right != null) {
  10.       best = Math.max(best, otherIslandsLeft + 2);
  11.       best = Math.max(best, dfs(node.left, otherIslandsLeft + 1));
  12.       best = Math.max(best, dfs(node.right, otherIslandsLeft + 1));
  13.     } else if (node.left != null && node.right == null) {
  14.       best = Math.max(best, otherIslandsLeft + 1);
  15.       best = Math.max(best, dfs(node.left, otherIslandsLeft));
  16.     } else if (node.left == null && node.right != null) {
  17.       best = Math.max(best, otherIslandsLeft + 1);
  18.       best = Math.max(best, dfs(node.right, otherIslandsLeft));
  19.     } // otherwise, null, null, do nothing
  20.     return best;
  21.   }
复制代码

评分

参与人数 1大米 +2 收起 理由
陈家洛 + 2 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
usr_opta 2020-9-6 14:00:06 | 只看该作者
全局:
本帖最后由 usr_opta 于 2020-9-6 14:07 编辑

和楼上做法其实一样
  1. struct Node {
  2.     Node *l = nullptr;
  3.     Node *r = nullptr;
  4. };

  5. // return number of islands if a path is removed from tree "p"
  6. int dp(Node* p) {
  7.     if (p->l == nullptr && p->r == nullptr) return 0;
  8.     if (p->l == nullptr) return dp(p->r);
  9.     if (p->r == nullptr) return dp(p->l);
  10.     return 1+max(dp(p->l), dp(p->r));
  11. }
复制代码


回复

使用道具 举报

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

本版积分规则

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