题意: 给定一棵二叉树,判断它是否为高度上平衡的。高度上平衡定义为每一个节点的左右子树的深度相差均不超过1。
分析: 本题主要考察二叉树的递归操作。递归得到每个节点左右子数的深度(叶子节点深度为1),判断左右子树相差是否超过1,如果超过1,将该节点深度设为-1,并向父亲节点返回结果,父亲节点得到左孩子或右孩子有深度为-1的,直接设置深度为-1。最终只需要判断root节点是否为正数,如果是则平衡,反之则不然。该方法只需遍历二叉树一次,时间复杂度为O(n)。
代码
public boolean isBalanced(TreeNode root){
if(root == null){
return true;
}else{
int height = getHeight(root);
if(height <= 0){
return false;
}else{
return true;
}
}
}
public int getHeight(TreeNode x){
int leftHeight = 0;
int rightHeight = 0;
if(x.left == null && x.right == null){ //叶子节点,递归终止条件
return 1;
}else{
if(x.left != null){
leftHeight = getHeight(x.left);
}
if(x.right != null){
rightHeight = getHeight(x.right);
}
if(leftHeight > rightHeight + 1 || rightHeight > leftHeight + 1 || leftHeight == -1 || rightHeight == -1){ //如果刚出现不平衡或者已经出现了不平衡就返回-1
return -1;
}else{ //否则返回较大的加1
return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);
}
}
}