Balanced Binary Tree

Sneha Michelle,TreesDepth-First Search

Problem Link

Balanced Binary Tree (opens in a new tab)

Problem Statement

Math.max(left,right)+1 Balanced Binary Tree: Math.abs(left,right)<1 A null tree is a balanced tree!


Algorithm

We need to go through each level -> DFS

Code

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