Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. public class IsTreeBalanced {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. // build a tree with Nodes...root is root Node
  6. isBalanced(root);
  7.  
  8. }
  9.  
  10. public static int getHeight(Node root) {
  11.  
  12. // base case, bottom of sub tree
  13. if (root == null) {
  14. return 0;
  15. }
  16.  
  17. // get height of left subtree, and check if it is balanced
  18. int heightLeft = getHeight(root.left);
  19. if (heightLeft == -1) {
  20. return -1;
  21. }
  22.  
  23. // get height of right subtree, and check if it is balanced
  24. int heightRight = getHeight(root.right);
  25. if (heightRight == -1) {
  26. return -1;
  27. }
  28.  
  29. // get difference between left and right, if > 1 they are unbalanced
  30. int heightDiff = Math.abs(heightRight - heightLeft);
  31. if (heightDiff > 1)
  32. return -1;
  33. else
  34. return Math.max(heightLeft, heightRight) + 1;
  35. }
  36.  
  37. public static void isBalanced(Node root) {
  38.  
  39. if (getHeight(root) == -1) {
  40. System.out.println("Tree not balanced");
  41. return;
  42. } else {
  43. System.out.println("Tree IS balanced!");
  44. }
  45. }
  46.  
  47.  
  48.  
  49. }
  50.  
  51. class Node {
  52.  
  53. int data;
  54. public Node left;
  55. public Node right;
  56.  
  57. public Node(int n) {
  58. data = n;
  59. left = null;
  60. right = null;
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement