manthanthakker40

Is_Balanced_BST

Jan 17th, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. public class Solution {
  11.     public boolean isBalanced(TreeNode root) {
  12.         int g=b(root);
  13.         if(g==-1)
  14.         return false;
  15.         return true;
  16.     }
  17.     public static int b(TreeNode root)
  18.     {
  19.         if(root==null)
  20.         return 0;
  21.         int l_h=b(root.left);
  22.         if(l_h==-1)
  23.         return -1;
  24.         int r_h=b(root.right);
  25.         if(r_h==-1)
  26.         return -1;
  27.         if(Math.abs(r_h-l_h)>1)
  28.         return -1;
  29.         else
  30.         return (1+Math.max(l_h,r_h));
  31.        
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment