TreeWork.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. public class TreeWork
  2. {
  3. private static int leftChild(int index)
  4. {
  5. return 2*index+1;
  6. }
  7. private static int rightChild(int index)
  8. {
  9. return 2*index+2;
  10. }
  11. public static<T extends Comparable<? super T>> boolean isHeap(T[] tree, int size)
  12. {
  13. return isHeap(tree, 0, size);
  14. }
  15. private static<T extends Comparable<? super T>> boolean isHeap(T[] tree, int start, int size)
  16. {
  17. if (leftChild(start) >= size)
  18. {
  19. return true;
  20. }
  21. else if (tree[leftChild(start)].compareTo(tree[start]) < 0)
  22. {
  23. return false;
  24. }
  25. else if (!isHeap(tree, leftChild(start), size))
  26. {
  27. return false;
  28. }
  29. else if (rightChild(start) >= size)
  30. {
  31. return true;
  32. }
  33. else if (tree[rightChild(start)].compareTo(tree[start]) < 0)
  34. {
  35. return false;
  36. }
  37. else if (!isHeap(tree, rightChild(start), size))
  38. {
  39. return false;
  40. }
  41. else
  42. {
  43. return true;
  44. }
  45. }
  46. public static<T> void printTree(T[] tree, int size)
  47. {
  48. for (int i = 0; i < size; i++)
  49. {
  50. if (i != 0 && (Math.log(i + 1)/Math.log(2)) % 1 == 0)
  51. {
  52. System.out.println();
  53. }
  54. System.out.print(tree[i] + " ");
  55. }
  56. System.out.println();
  57. }
  58. }