Guest User

Untitled

a guest
Feb 18th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. package com.example.tree;
  2. import com.example.Node;
  3. // Tree is balanced when the difference between maximum and minimum height is <= 1.
  4. public class Tree{
  5.  
  6. public static void main(String args[]){
  7. Node root = new Node();
  8. if(checkTreeBalance(root))
  9. System.out.println("Its a balanced tree");
  10. else
  11. System.out.println("Its not a balanced tree");
  12. }
  13.  
  14. public static boolean checkTreeBalance(Node root){
  15. return (maxHeight(root) - minHeight(root)) <= 1 ;
  16. }
  17.  
  18. public static int maxHeight(Node root){
  19. if(root == null)
  20. return 0;
  21.  
  22. return 1 + Math.max(maxHeight(root.getLeft()),maxHeight(root.getRight()));
  23. }
  24.  
  25. public static int minHeight(Node root){
  26. if(root == null)
  27. return 0;
  28.  
  29. return 1 + Math.min(minHeight(root.getLeft()),minHeight(root.getRight()));
  30.  
  31. }
  32.  
  33. }
Add Comment
Please, Sign In to add comment