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

[学Java/C#] 333题,43行为啥要比较 Math.min(left.lower, root.val)

全局:

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

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

x
本帖最后由 zurich.hill 于 2020-8-25 01:46 编辑

如题,难道,left.lower, root.val,不是已经是left.lower会更小吗,为啥要重复比较一下呢?

  1. public class Solution {

  2.             /** 初始化 结果  */
  3.             int max = 0;

  4.             /** 主函数 */
  5.             public int largestBSTSubtree(TreeNode root) {

  6.                 /** 边界条件 */
  7.                 if (root == null) { return 0; }

  8.                 traverse(root);

  9.                 return max;
  10.             }

  11.             /** 开始战斗 */
  12.             private sub_BST traverse(TreeNode root) {

  13.                 /** 如果root是空,边界条件 */
  14.                 if (root == null) { return new sub_BST(0, Integer.MAX_VALUE, Integer.MIN_VALUE); }

  15.                 /** 左右测试 */
  16.                 sub_BST left = traverse(root.left);
  17.                 sub_BST right = traverse(root.right);

  18.                 /** 假如不合格 */
  19.                 if (       left.size == -7
  20.                         || right.size == -7
  21.                         || root.val <= left.upper /** BST不合格 */
  22.                         || root.val >= right.lower /** BST不合格 */)
  23.                 {
  24.                     return new sub_BST( -7 /** -7只是一个编号,说明错误  */, Integer.MAX_VALUE, Integer.MIN_VALUE);
  25.                 }

  26.                 /** 假如左右树都是BST,那么两边size相加 */
  27.                 int size = left.size + 1 + right.size;

  28.                 /** 找到max */
  29.                 max = Math.max(size, max);

  30.                 /** 返回BST,和它的最大,最小值 */
  31.                 return new sub_BST(size, Math.min(left.lower, root.val), Math.max(right.upper, root.val));
  32.             }
  33.         }

  34. /** 子class */
  35. class sub_BST {

  36.     int size;

  37.     int lower;
  38.     int upper;

  39.     sub_BST(int size, int lower, int upper) {

  40.         this.size = size;
  41.         this.lower = lower;   // 樹的最小值
  42.         this.upper = upper;   // 樹的最大值
  43.     }

  44. }
复制代码

评分

参与人数 2大米 +2 收起 理由
pennyhwung + 1 赞一个
14417335 + 1 欢迎分享你知道的情况

查看全部评分


上一篇:LeetCode 543 求解。为何不是 Left + Right + 1
下一篇:聊聊HashMap 和 HashTable 区别
全局:
因为left. lower可能是Integer. MAX_VALIE

评分

参与人数 1大米 +1 收起 理由
zurich.hill + 1 欢迎分享你知道的情况,会给更多积分奖励!

查看全部评分

回复

使用道具 举报

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

本版积分规则

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