LeetCode 110. Balanced Binary Tree 判断是否为平衡二叉树(Java)

题目:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

LeetCode 110. Balanced Binary Tree 判断是否为平衡二叉树(Java)_第1张图片

解答:

思路:

  1. 计算每个节点的高度,通过maxDepth()递归来得出左右子树的深度
  2. 从根节点开始从上往下遍历,判断每个节点的左右子树是否是平衡的,通过isBalanced()递归判断平衡树
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        int leftdepth=maxDepth(root.left);
        int rightdepth=maxDepth(root.right);
        if(Math.abs(leftdepth-rightdepth)>1){
            return false;
        }
        return (isBalanced(root.left)&&isBalanced(root.right));
    }
    private int maxDepth(TreeNode node){
        if(node==null){
            return 0;
        }
        return Math.max(maxDepth(node.left),maxDepth(node.right))+1;
    }
}

注意:平衡二叉树是指每个节点都满足指左右子树的高度差小于1
在首次提交答案时,忽略了每个节点的递归判断,导致结果出错
LeetCode 110. Balanced Binary Tree 判断是否为平衡二叉树(Java)_第2张图片
LeetCode 110. Balanced Binary Tree 判断是否为平衡二叉树(Java)_第3张图片

你可能感兴趣的:(LeetCode)