剑指 Offer 55 - II. 平衡二叉树(递归)

题目
在这里插入图片描述
判断是否为平衡二叉树需要判断每一个结点的左右子树深度相差是否不超过1
第一时间想到了递归 然后过程中用一个flag记录是否平衡 后来去题解学习了一遍nb的写法
全局flag法

class Solution {
    
    
    boolean flag = true;
    public int getDeep(TreeNode root){
    
    
        if (root == null) return 0;
        return Math.max(getDeep(root.left),getDeep(root.right))+1;
    }
   public boolean isBalanced(TreeNode root) {
    
    
        if (root == null) return true;
        if (Math.abs(getDeep(root.left) - getDeep(root.right)) > 1) {
    
    
            flag = false;
            return false;
        }
        isBalanced(root.left);
        isBalanced(root.right);
        if (flag == false) return false;
        return true;
    }
}

nb写法

    public int getDeep(TreeNode root){
    
    
        if (root == null) return 0;
        return Math.max(getDeep(root.left),getDeep(root.right))+1;
    }
    public boolean isBalanced(TreeNode root) {
    
    
        if (root == null) return true;
        return (Math.abs(getDeep(root.left)-getDeep(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right));
    }

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/115114798