Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1.  
  2. public class ArrayHeapChecker {
  3. //Check if the given array is a representation of a binary tree
  4. public static boolean isBinaryTree(Integer[] array) {
  5. if (array == null) {
  6. return false;
  7. }
  8.  
  9. else if (array.length == 1 || array.length == 0) {
  10. return true;
  11. }
  12.  
  13. for (int i=1; i<array.length; i++) {
  14. if (array[i]!=null && array[(int)((i-1)/2)]== null) {
  15. return false;
  16. }
  17. }
  18.  
  19. return true;
  20. }
  21.  
  22. //Check if the given array is a complete binary tree
  23. public static boolean isCompleteBinaryTree(Integer[] array) {
  24. if(!isBinaryTree(array)) {
  25. return false;
  26. }
  27. // If index assigned to current node is more than number of nodes in tree, then tree is not complete
  28. int numberOfNodes = 0;
  29. for (int i=0; i<array.length; i++) {
  30. if (array[i]!=null) {
  31. numberOfNodes++;
  32. }
  33. }
  34.  
  35. for (int j=0; j<array.length; j++) {
  36. if (array[j]!=null && j >= numberOfNodes) {
  37. return false;
  38. }
  39. }
  40. return true;
  41. }
  42.  
  43. //Check if the given array is a min-heap
  44. public static boolean isMinHeap(Integer[] array) {
  45. if(!isCompleteBinaryTree(array)) {
  46. return false;
  47. }
  48.  
  49. for (int i=1; i<array.length; i++) {
  50. if (array[i]!=null && (array[(int)((i-1)/2)] > array[i])) {
  51. return false;
  52. }
  53. }
  54. return true;
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement