Bottom up O(n) short Java solution


  • 0
    M
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        boolean res = true;
        public boolean isBalanced(TreeNode root) {
            balanced(root);
            return res;
        }
        
        public int balanced(TreeNode root) {
            if(root == null) return 0;
            int left = balanced(root.left);
            int right = balanced(root.right);
            if(Math.abs(right - left) > 1) res = false;
            return Math.max(left, right) + 1;
        }
    }
    

Log in to reply
 

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