题目链接Balanced Binary Tree
判断一个二叉树是否为平衡二叉树
平衡二叉树的定义为:每个节点的两个子树的深度相差不会超过1,即根节点的两个子树的深度相差不超过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;
if(depth(root.left)-depth(root.right)>1||depth(root.right)-depth(root.left)>1)
return false;
else
return isBalanced(root.left)&&isBalanced(root.right);
}
//计算树的深度
public int depth(TreeNode root){
if(root==null)
return 0;
int depthl = depth(root.left);
int depthr = depth(root.right);
int dep = 1 + ((depthl>depthr)?depthl:depthr);
return dep;
}
}