modify code

master
algorithmzuo 3 years ago
parent d43c75ff2d
commit a3072591d5

@ -12,56 +12,68 @@ public class Code04_IsFull {
}
}
// 第一种方法
// 收集整棵树的高度h和节点数n
// 只有满二叉树满足 : 2 ^ h - 1 == n
public static boolean isFull1(Node head) {
if (head == null) {
return true;
}
int height = h(head);
int nodes = n(head);
return (1 << height) - 1 == nodes;
Info1 all = process1(head);
return (1 << all.height) - 1 == all.nodes;
}
public static int h(Node head) {
if (head == null) {
return 0;
public static class Info1 {
public int height;
public int nodes;
public Info1(int h, int n) {
height = h;
nodes = n;
}
return Math.max(h(head.left), h(head.right)) + 1;
}
public static int n(Node head) {
public static Info1 process1(Node head) {
if (head == null) {
return 0;
return new Info1(0, 0);
}
return n(head.left) + n(head.right) + 1;
Info1 leftInfo = process1(head.left);
Info1 rightInfo = process1(head.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
int nodes = leftInfo.nodes + rightInfo.nodes + 1;
return new Info1(height, nodes);
}
// 第二种方法
// 收集子树是否是满二叉树
// 收集子树的高度
// 左树满 && 右树满 && 左右树高度一样 -> 整棵树是满的
public static boolean isFull2(Node head) {
if (head == null) {
return true;
}
Info all = process(head);
return (1 << all.height) - 1 == all.nodes;
return process2(head).isFull;
}
public static class Info {
public static class Info2 {
public boolean isFull;
public int height;
public int nodes;
public Info(int h, int n) {
public Info2(boolean f, int h) {
isFull = f;
height = h;
nodes = n;
}
}
public static Info process(Node head) {
if (head == null) {
return new Info(0, 0);
public static Info2 process2(Node h) {
if (h == null) {
return new Info2(true, 0);
}
Info leftInfo = process(head.left);
Info rightInfo = process(head.right);
Info2 leftInfo = process2(h.left);
Info2 rightInfo = process2(h.right);
boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
int nodes = leftInfo.nodes + rightInfo.nodes + 1;
return new Info(height, nodes);
return new Info2(isFull, height);
}
// for test
@ -84,13 +96,14 @@ public class Code04_IsFull {
int maxLevel = 5;
int maxValue = 100;
int testTimes = 1000000;
System.out.println("测试开始");
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
if (isFull1(head) != isFull2(head)) {
System.out.println("Oops!");
System.out.println("出错了!");
}
}
System.out.println("finish!");
System.out.println("测试结束");
}
}

Loading…
Cancel
Save