Java - check height


  • 0

    '''
    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      class Solution {
      public boolean isBalanced(TreeNode root) {
      if(root == null)
      return true;
      int left = height(root.left);
      int right = height(root.right);

       if(Math.abs(left-right)>1)
           return false;
       
       return isBalanced(root.left) && isBalanced(root.right);
      
    }
    
    int height(TreeNode root){
        if(root == null)
            return 0;
        return 1 + Math.max(height(root.left),height(root.right));
    }
    

    }
    '''


Log in to reply
 

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