一、题目
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
二、解题思路
想要知道一棵二叉树是否平衡,可以查看该树每个节点的左右子树的深度是否相差的绝对值<=1。
三、求树高度模板
//求树的高度
public int height(TreeNode root) {
if(root==null) {
return 0;
}
return Math.max(height(root.left), height(root.right))+1;
}
三、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) {
return true;
}
return Math.abs(height(root.left)-height(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
//求树的高度
public int height(TreeNode root) {
if(root==null) {
return 0;
}
return Math.max(height(root.left), height(root.right))+1;
}
}
四、运行结果