Simple Java Solution - Using 1 helper function


  • 0

    public class Solution {

    public boolean isBalanced(TreeNode root) {
        if (root == null) return true; 
        
        boolean isB = true; 
        int left_h = dep(root.left); 
        int right_h = dep(root.right); 
        
        if ( Math.abs(left_h - right_h) > 1||
             isBalanced(root.left) == false||
             isBalanced(root.right) == false )
          isB = false;
        
        return isB; 
    }
    
    private int dep(TreeNode root){
        if (root == null) return 0; 
        return 1 + Math.max(dep(root.left), dep(root.right)); 
    } 
    

    }


  • 0
    T

    @zzhai Thanks for the solution. I really find one really long line of code unreadable. I had to separate all the conditions in the if statement to make it more readable. But thanks for the solution.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.