实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
利用递归实现:需要遍历树的每一个节点。拿到根节点的左子树的深度和右子树的深度,若根节点的左右子树的深度相差大于1的话,那么不是 一颗平衡二叉树,递归检查根节点的左子树和右子树。其实最后会遍历树中的所有节点,除非返回false。
/**
* 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;
//拿到节点的左子树和右子树的深度
int deptLeft = getDept(root.left, 0);
int deptRight = getDept(root.right, 0);
//如果相差大于1,那么不是一颗平衡树
if (Math.abs(deptLeft - deptRight) > 1)
return false;
//递归检查这个节点的左子节点和右子节点
return isBalanced(root.left) && isBalanced(root.right);
}
//获取从某个节点开始的深度
private int getDept(TreeNode root, int dept) {
if (root == null)
return dept;
int deptLeft = getDept(root.left, dept + 1);
int deptRight = getDept(root.right, dept + 1);
return Math.max(deptLeft, deptRight);
}
}