本文涉及到的代码在我的github中的Balance.java中。
题目描述:
实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。
思路分析:
求得左子树深度和右子树深度,如果差别大于1,那么返回false,否则对左右子树分别递归判断。
代码如下:
package newcoder;
import java.util.*;
class TreeNode
{
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val)
{
this.val = val;
}
}
public class Balance
{
public boolean isBalance(TreeNode root)
{
// write code here
if (root == null)
return true;
int left = getDepth(root.left);//左子树深度
int right = getDepth(root.right);//右子树深度
if (Math.abs(left - right) > 1)
return false;
return isBalance(root.left) && isBalance(root.right);
}
//求树的深度
public int getDepth(TreeNode root)
{
if (root == null)
return 0;
int leftDepth = getDepth(root.left);//左子树深度
int rightDepth = getDepth(root.right);//右子树深度
return Math.max(leftDepth, rightDepth) + 1;//总深度
}
}