深度优先搜索树,得到左子树高度和右子树高度,如果两个高度差超过1,则不是平衡树
public class MyTest1 {
private boolean isBalance = true;
public boolean isBalanced(TreeNode root) {
dfs(root);
return isBalance;
}
/**
* 深度优先,遍历树,返回树的高度
* @param root
* @return
*/
private int dfs(TreeNode root) {
if(root==null) {
return 0;
}
int leftDepth = dfs(root.left);
int rightDepth = dfs(root.right);
if(Math.abs(rightDepth-leftDepth)>1) {
isBalance = false;
}
return Math.max(leftDepth, rightDepth)+1;
}
}