From afc54776e8ed3b40397360b4cfe07812e2a1c42a Mon Sep 17 00:00:00 2001 From: algorithmzuo Date: Mon, 20 Jun 2022 15:43:16 +0800 Subject: [PATCH] modify code --- src/class12/Code05_MaxSubBSTSize.java | 78 ++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/src/class12/Code05_MaxSubBSTSize.java b/src/class12/Code05_MaxSubBSTSize.java index ac8c8e5..85ee0cd 100644 --- a/src/class12/Code05_MaxSubBSTSize.java +++ b/src/class12/Code05_MaxSubBSTSize.java @@ -1,5 +1,7 @@ package class12; +import java.util.ArrayList; + // 在线测试链接 : https://leetcode.com/problems/largest-bst-subtree public class Code05_MaxSubBSTSize { @@ -14,7 +16,7 @@ public class Code05_MaxSubBSTSize { } } - // 提交如下的代码,可以直接通过 + // 提交如下的largestBSTSubtree方法,可以直接通过 public static int largestBSTSubtree(TreeNode head) { if (head == null) { return 0; @@ -78,4 +80,78 @@ public class Code05_MaxSubBSTSize { return new Info(Math.max(p1, Math.max(p2, p3)), allSize, max, min); } + // 为了验证 + // 对数器方法 + public static int right(TreeNode head) { + if (head == null) { + return 0; + } + int h = getBSTSize(head); + if (h != 0) { + return h; + } + return Math.max(right(head.left), right(head.right)); + } + + // 为了验证 + // 对数器方法 + public static int getBSTSize(TreeNode head) { + if (head == null) { + return 0; + } + ArrayList arr = new ArrayList<>(); + in(head, arr); + for (int i = 1; i < arr.size(); i++) { + if (arr.get(i).val <= arr.get(i - 1).val) { + return 0; + } + } + return arr.size(); + } + + // 为了验证 + // 对数器方法 + public static void in(TreeNode head, ArrayList arr) { + if (head == null) { + return; + } + in(head.left, arr); + arr.add(head); + in(head.right, arr); + } + + // 为了验证 + // 对数器方法 + public static TreeNode generateRandomBST(int maxLevel, int maxValue) { + return generate(1, maxLevel, maxValue); + } + + // 为了验证 + // 对数器方法 + public static TreeNode generate(int level, int maxLevel, int maxValue) { + if (level > maxLevel || Math.random() < 0.5) { + return null; + } + TreeNode head = new TreeNode((int) (Math.random() * maxValue)); + head.left = generate(level + 1, maxLevel, maxValue); + head.right = generate(level + 1, maxLevel, maxValue); + return head; + } + + // 为了验证 + // 对数器方法 + public static void main(String[] args) { + int maxLevel = 4; + int maxValue = 100; + int testTimes = 1000000; + System.out.println("测试开始"); + for (int i = 0; i < testTimes; i++) { + TreeNode head = generateRandomBST(maxLevel, maxValue); + if (largestBSTSubtree(head) != right(head)) { + System.out.println("出错了!"); + } + } + System.out.println("测试结束"); + } + }