How many nodes does a 10-layer binary tree contain at most?
Note: When a binary tree has only one node, it is a layer.
Idea: When you look at the piece, you know that it must be a moth. I drew a five-layer binary tree directly on the book. After finding the rule, I directly wrote the code. The rule is 2 to the power of 10. Answer: 1023
This solution of the first kind really looks like a han han -.- #
public class Main {
public static void main(String[] args) {
int n1 = 1;
int n2 = 2;
int n3 = n2 * 2;
int n4 = n3 * 2;
int n5 = n4 * 2;
int n6 = n5 * 2;
int n7 = n6 * 2;
int n8 = n7 * 2;
int n9 = n8 * 2;
int n10 = n9 * 2;
System.out.println(n10 + n9 + n8 + n7 + n6 + n5 + n4 + n3 + n2 + n1);
}
}
In the second solution, the problem requires that the first layer be fixed at 1, and then enumerate 9 layers.
public class Main {
public static void main(String[] args) {
int ans = 1;
int num = 1;
for (int i = 1; i <= 9; i++) {
num *= 2;
ans += num; // 10层节点相加
}
System.out.println(ans);
}
}
The third solution, according to the law is 2 to the power of 10 -1, remember to give int type.
public class Main {
public static void main(String[] args) {
System.out.println((int) Math.pow(2, 10) - 1);
}
}