diff --git a/src/class30/Code05_MinHeight.java b/src/class30/Code02_MinDepth.java similarity index 54% rename from src/class30/Code05_MinHeight.java rename to src/class30/Code02_MinDepth.java index 9814825..fa2160c 100644 --- a/src/class30/Code05_MinHeight.java +++ b/src/class30/Code02_MinDepth.java @@ -1,18 +1,21 @@ package class30; -public class Code05_MinHeight { +// 本题测试链接 : https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/ +public class Code02_MinDepth { - public static class Node { + // 不提交这个类 + public static class TreeNode { public int val; - public Node left; - public Node right; + public TreeNode left; + public TreeNode right; - public Node(int x) { + public TreeNode(int x) { val = x; } } - public static int minHeight1(Node head) { + // 下面的方法是一般解 + public static int minDepth1(TreeNode head) { if (head == null) { return 0; } @@ -20,7 +23,7 @@ public class Code05_MinHeight { } // 返回x为头的树,最小深度是多少 - public static int p(Node x) { + public static int p(TreeNode x) { if (x.left == null && x.right == null) { return 1; } @@ -36,13 +39,13 @@ public class Code05_MinHeight { return 1 + Math.min(leftH, rightH); } - // 根据morris遍历改写 - public static int minHeight2(Node head) { + // 下面的方法是morris遍历的解 + public static int minDepth2(TreeNode head) { if (head == null) { return 0; } - Node cur = head; - Node mostRight = null; + TreeNode cur = head; + TreeNode mostRight = null; int curLevel = 0; int minHeight = Integer.MAX_VALUE; while (cur != null) { @@ -82,37 +85,4 @@ public class Code05_MinHeight { return minHeight; } - // for test - public static Node generateRandomBST(int maxLevel, int maxValue) { - return generate(1, maxLevel, maxValue); - } - - // for test - public static Node generate(int level, int maxLevel, int maxValue) { - if (level > maxLevel || Math.random() < 0.5) { - return null; - } - Node head = new Node((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 treeLevel = 7; - int nodeMaxValue = 5; - int testTimes = 100000; - System.out.println("test begin"); - for (int i = 0; i < testTimes; i++) { - Node head = generateRandomBST(treeLevel, nodeMaxValue); - int ans1 = minHeight1(head); - int ans2 = minHeight2(head); - if (ans1 != ans2) { - System.out.println("Oops!"); - } - } - System.out.println("test finish!"); - - } - }