Leetcode:110. 平衡二叉树

要点:本题的本质还是求二叉树的深度。编写一个函数depth用于求子树的深度,得出的左右子树之差的绝对值如果大于1,那么这棵树不是平衡二叉树,否则该树为平衡二叉树。

class Solution {
    boolean result = true;
    public boolean isBalanced(TreeNode root) {
        depth(root);
        return result;
    }

    public int depth(TreeNode root){
        if(root == null) return 0;
        int l = depth(root.left);
        int r = depth(root.right);
        
        if(Math.abs(l - r) > 1) result = false;
        
        return Math.max(l , r) + 1;
    }
}

1 声望1 粉丝

引用和评论

0 条评论