给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
答案:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isBalanced(TreeNode root) { return height(root) >= 0; } public int height(TreeNode root) { if(root == null) { return 0; } int left = height(root.left); int right = height(root.right); //判断条件是???left >= 0 && right >= 0,有可能返回-1 if(left >= 0 && right >= 0 && Math.abs(left - right) <= 1) { return Math.max(right, left) + 1; } else { return -1; } } }