📣 Back to School开学季 - VIP通行证5折优惠!蓝莓、Offer多多同步优惠
123
返回列表 发新帖
楼主: shenji
跳转到指定楼层
上一主题 下一主题
收起左侧

Doordash Phone Screen

🔗
litJordan 2022-3-5 09:01:54 | 只看该作者
全局:
  1. private static int max = Integer.MIN_VALUE;
  2.     private static int maxPathSum(TreeNode root) {
  3.         dfs(root);
  4.         return max;
  5.     }
  6.    
  7.     // Use Integer as return type to distinguish between a true MIN_VALUE or it's null
  8.     public static Integer dfs(TreeNode node) {
  9.         if (node == null)
  10.             return null;
  11.         // find the alive node, return its value
  12.         if (node.left == null && node.right == null && node.hasAst) {
  13.             return node.val;
  14.         }
  15.         int val = node.val;
  16.         Integer left = dfs(node.left);
  17.         Integer right = dfs(node.right);
  18.         // if both children are not null, means we find a path that travels from one alive node to another
  19.         if (left != null && right != null) {
  20.             max = Math.max(max, left + val + right);
  21.         }
  22.         Integer leftMax = left == null ? null : left + val;
  23.         Integer rightMax = right == null ? null : right + val;
  24.         // if either leftMax or rightMax is null, it means one of these path is not leading to an alive node, so return the non null path max
  25.         if (leftMax == null || rightMax == null)
  26.             return leftMax != null ? leftMax : rightMax;
  27.         return Math.max(leftMax, rightMax);
  28.     }
复制代码
回复

使用道具 举报

🔗
倩小小花 2022-10-22 09:45:33 | 只看该作者
全局:
xiaozhuxiaozhu 发表于 2021-9-10 19:06
感谢分享, 如果我理解题意了。 这题可能可以直接用recursion做。 第一问。 下面代码是考虑了负数的存在, ...

您好,请问follow up的话在您的思路基础上应该怎么改呢?谢谢。
回复

使用道具 举报

全局:
xiaozhuxiaozhu 发表于 2021-9-10 16:06
感谢分享, 如果我理解题意了。 这题可能可以直接用recursion做。 第一问。 下面代码是考虑了负数的存在, ...

"两个alive nodes路径上不能有其它的alive nodes" => 你的算法不符合这个要求。
回复

使用道具 举报

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

本版积分规则

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