分析:
共有两种解法:如果是满二叉树,其满足二叉树的节点数量 =
2
n
−
1
2^n - 1
2n−1 。其中n为二叉树的层数。
所以可以获取到该数的高度和总共的节点数,进行判断。
还可以根据判断左右子树是否是满二叉树,以及左右子树的层高来判断。
public static class Node {
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}
第一种解法
public static class Info1 {
int height;
boolean isFull;
public Info1(int height, boolean isFull) {
this.height = height;
this.isFull = isFull;
}
}
public static boolean isFull1(Node head) {
if (head == null) {
return true;
}
return process1(head).isFull;
}
public static Info1 process1(Node head) {
if (head == null) {
return new Info1(0, true);
}
Info1 leftInfo = process1(head.left);
Info1 rightInfo = process1(head.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;
return new Info1(height, isFull);
}
第二种解法
public static class Info2 {
int height;
int nodes;
public Info2(int height, int nodes) {
this.height = height;
this.nodes = nodes;
}
}
public static boolean isFull2(Node head) {
if (head == null) {
return true;
}
Info2 result = process2(head);
return (1 << result.height) - 1 == result.nodes;
}
public static Info2 process2(Node head) {
if (head == null) {
return new Info2(0, 0);
}
Info2 leftInfo = process2(head.left);
Info2 rightInfo = process2(head.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
int nodes = leftInfo.nodes + rightInfo.nodes + 1;
return new Info2(height, nodes);
}