[leetcode]110BalancedBinaryTree平衡二叉树

public boolean isBalanced(TreeNode root) {
        int res = helper(root);
        if (res<0) return false;
        return true;
    }
    public int helper(TreeNode root)
    {
        if (root==null) return 0;
        //从底下开始判断是否平衡树
        //两个变量如果是-1就代表是不平衡
        int ld = helper(root.left);
        int rd = helper(root.right);
        //三种情况就不平衡:左右子树不平衡,本节点不平衡
        if (ld==-1||rd==-1||Math.abs(ld-rd)>1)
            return -1;
        else if (ld>rd) return ld+1;
        else return rd+1;
    }

 

posted @ 2018-01-25 19:20  stAr_1  阅读(95)  评论(0编辑  收藏  举报