【DFS】LeetCode 110. 平衡二叉树

发布时间 2023-03-29 09:39:39作者: Frodo1124

题目链接

110. 平衡二叉树

思路

一个空树肯定是平衡二叉树,并且一个平衡二叉树的子树也是平衡二叉树。利用这两条性质我们可以推断出代码中含有 root == null -> return trueisBalanced(root.left) && isBalanced(root.right)

又因为平衡二叉树的条件是左右子树高度差不超过1,所以我们可以得到判断条件 Math.abs(height(root.left) - height(root.right)) <= 1

综上,一共有两个结束递归的条件:

  • root == null -> return true
  • isBalanced(root.left) && isBalanced(root.right) && 高度差不超过1 -> return true

其余情况都 return false

代码

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        if(Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right)){
            return true;
        }

        return false;
    }

    private int height(TreeNode node){
        if(node == null){
            return 0;
        }

        return Math.max(height(node.left), height(node.right)) + 1;
    }
}