1. /**
    2. * 满二叉树
    3. * 高度为h的满二叉树的节点数为 2^h - 1
    4. */
    5. public class Code04_IsFull {
    6. public static class Node {
    7. public int value;
    8. public Node left;
    9. public Node right;
    10. public Node(int data) {
    11. this.value = data;
    12. }
    13. }
    14. public static boolean isFull1(Node head) {
    15. if (head == null) {
    16. return true;
    17. }
    18. int height = h(head);
    19. int nodes = n(head);
    20. return (1 << height) - 1 == nodes;
    21. }
    22. public static int h(Node head) {
    23. if (head == null) {
    24. return 0;
    25. }
    26. return Math.max(h(head.left), h(head.right)) + 1;
    27. }
    28. public static int n(Node head) {
    29. if (head == null) {
    30. return 0;
    31. }
    32. return n(head.left) + n(head.right) + 1;
    33. }
    34. public static boolean isFull2(Node head) {
    35. if (head == null) {
    36. return true;
    37. }
    38. Info all = process(head);
    39. return (1 << all.height) - 1 == all.nodes;
    40. }
    41. public static class Info {
    42. public int height;
    43. public int nodes;
    44. public Info(int h, int n) {
    45. height = h;
    46. nodes = n;
    47. }
    48. }
    49. public static Info process(Node head) {
    50. if (head == null) {
    51. return new Info(0, 0);
    52. }
    53. Info leftInfo = process(head.left);
    54. Info rightInfo = process(head.right);
    55. int height = Math.max(leftInfo.height, rightInfo.height) + 1;
    56. int nodes = leftInfo.nodes + rightInfo.nodes + 1;
    57. return new Info(height, nodes);
    58. }
    59. // for test
    60. public static Node generateRandomBST(int maxLevel, int maxValue) {
    61. return generate(1, maxLevel, maxValue);
    62. }
    63. // for test
    64. public static Node generate(int level, int maxLevel, int maxValue) {
    65. if (level > maxLevel || Math.random() < 0.5) {
    66. return null;
    67. }
    68. Node head = new Node((int) (Math.random() * maxValue));
    69. head.left = generate(level + 1, maxLevel, maxValue);
    70. head.right = generate(level + 1, maxLevel, maxValue);
    71. return head;
    72. }
    73. public static void main(String[] args) {
    74. int maxLevel = 5;
    75. int maxValue = 100;
    76. int testTimes = 1000000;
    77. for (int i = 0; i < testTimes; i++) {
    78. Node head = generateRandomBST(maxLevel, maxValue);
    79. if (isFull1(head) != isFull2(head)) {
    80. System.out.println("Oops!");
    81. }
    82. }
    83. System.out.println("finish!");
    84. }
    85. }