Balanced Binary Tree——my solution


  • 0
    W
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        boolean ret = true;
        public boolean isBalanced(TreeNode root) {
            if(root == null)return true;
            int b = WBalanced(root.left) - WBalanced(root.right);
            if(ret == false || b > 1 || b < -1){
                return false;
            }
            return true;
        }
    
        int WBalanced(TreeNode root){
            if(root == null)return 0;
            int left = WBalanced(root.left),right = WBalanced(root.right),m = left - right;
            if(m > 1 || m < -1)ret = false;
            return (left >= right?left:right) + 1;
        }
    }

Log in to reply
 

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