Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. package weblab;
  2. import java.lang.Math;
  3. class Solution {
  4.  
  5. /**
  6. * Computes whether the BinaryTree is an AVL tree.
  7. *
  8. * @param tree
  9. * the BinaryTree to check.
  10. * @return true iff the BinaryTree is an AVL tree, else false.
  11. */
  12. public static boolean isTreeAVL(BinaryTree tree) {
  13. return isTreeBST(tree, Integer.MIN_VALUE, Integer.MAX_VALUE);
  14. }
  15.  
  16.  
  17. public static boolean isTreeBST(BinaryTree tree, int min, int max){
  18.  
  19. if (tree == null){
  20. return true;
  21. }
  22.  
  23. if (tree.getKey() <= min || tree.getKey() >= max){
  24. return false;
  25. }
  26.  
  27.  
  28.  
  29. if (tree.hasLeft()){
  30. if(!isTreeBST(tree.getLeft(), min, tree.getKey())){
  31. return false;
  32. }
  33. }
  34.  
  35. if (tree.hasRight()){
  36. if(!isTreeBST(tree.getRight(), tree.getKey(), max)){
  37. return false;
  38. }
  39. }
  40.  
  41. if ((size(tree.getRight())- size(tree.getLeft()) > 1 || (size(tree.getRight())- size(tree.getLeft())) < -1 )){
  42. return false;
  43. }
  44.  
  45. return true;
  46. }
  47.  
  48. public static int size(BinaryTree tree){
  49. if (tree == null){
  50. return 0;
  51. }
  52. return 1 + Math.max(size(tree.getRight()), size(tree.getLeft()));
  53. }
  54.  
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement