> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-06-2022-110.md).

# 01/06/2022 110

//top-down approach

```
//topdown approach 
if(root == null) return true; 
if(root.left == null && root.right == null) return true; 
return Math.abs(height(root.left) - height(root.right)) <2 && isBalanced(root.left) && isBalanced(root.right);
}

private int height(TreeNode root){
    if (root == null) return 0;
    return Math.max(height(root.left),height(root.right)) + 1;
    
}
```

```
//Optimized one
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        else if (root.left==null && root.right==null) return true;
        else return dfs(root)!=-1;
    }
    
    private int dfs(TreeNode root){
        if(root==null) return 0;
        
        int leftHeight= dfs(root.left);
        if(leftHeight==-1) return -1;
        int rightHeight= dfs(root.right);
        if(rightHeight==-1) return -1;
        
        if (Math.abs(leftHeight-rightHeight)>1) return -1;
        else return 1+Math.max(leftHeight,rightHeight);
    }
}
```
