Java 1ms solution


  • 0
    W
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root==null) return true;
            int left= treeHeight(root.left);
            int right = treeHeight(root.right);
            return (left==-1 || right ==-1)? false:
                   left>right?  
                   left-right<=1:
                   right-left<=1;
        }
        private int treeHeight(TreeNode root){
            if(root == null) return 1;
            int left = treeHeight(root.left);
            int right = treeHeight(root.right);
            if(left==-1 ||right== -1) return -1;
            if(left>right)
                return left-right<=1 ? 1+left :-1 ;
            else
                return right-left<=1 ? 1+right :-1 ;
        }
    }
    

  • 0
    K

    Here is my solution with same idea.

        public boolean isBalanced(TreeNode root) {
            return getDepth(root) != -1;
        }
        
        private int getDepth(TreeNode node) {
            if(node == null) {
                return 0;
            }
            int rd = getDepth(node.right);
            int ld = getDepth(node.left);
            if(rd == -1 || ld == -1) {
                return -1;
            }
            if(Math.abs(rd - ld) <= 1) {
                return 1 + Math.max(rd, ld);
            }
            return -1;
        }
    

Log in to reply
 

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