Advertisement
MuzammiL5

Is Balanced Binary Tree

Jun 3rd, 2023
899
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.40 KB | None | 0 0
  1. public boolean isBalanced(TreeNode root) {
  2.     return height(root) >= 0;
  3. }
  4.  
  5. int height(TreeNode root) {
  6.     if (root == null)
  7.         return 0;
  8.     int l, r;
  9.  
  10.     l = height(root.left);
  11.     if (l == -1)
  12.         return -1;
  13.     r = height(root.right);
  14.     if (r == -1)
  15.         return -1;
  16.     if (Math.abs(l-r) > 1) {
  17.         return -1;
  18.     } else {
  19.         return Math.max(l, r) + 1;
  20.     }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement