题目要求:判断一个二叉树是否为平衡二叉树(该二叉树的所有节点的左右子树高度差不能超过1)
tags:tree,depth-first search recursive
我的思路:
1.遍历所有的节点,获取其左右子树的高度
2.计算左右子树的高度差,如果有大于1的,则为非平衡二叉树,如果全部满足,则为平衡二叉树。
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
int minus = treeHeight(root.left)-treeHeight(root.right);
if(minus>=-1&&minus<=1){
return isBalanced(root.left)&&isBalanced(root.right);
}else{
return false;
}
}
public int treeHeight(TreeNode root){
if(root!=null){
return 1+Math.max(treeHeight(root.left),treeHeight(root.right));
}else{
return 0;
}
}
另一种思路:使用dfs
public boolean isBalanced2(TreeNode root){
return dfsHeight(root)!=-1;
}
public int dfsHeight(TreeNode root){
if(root==null){
return 0;
}
int leftHeight = dfsHeight(root.left);
if(leftHeight==-1){
return -1;
}
int rightHeight = dfsHeight(root.right);
if(rightHeight==-1){
return -1;
}
if(Math.abs(leftHeight-rightHeight)>1){
return -1;
}
return 1+Math.max(leftHeight, rightHeight);
}