题目描述
实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。
给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。
解法一:(递归解法,但是getHeight()没有任何优化,同一个节点的高度可能会计算多次) 复杂度 Nlog(N)
import java.util.*;
/*
public 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) {
if(root==null) return true;
int diff=Math.abs(getHeight(root.left)-getHeight(root.right));
if(diff>1) return false;
return isBalance(root.left)&&isBalance(root.right);
}
private int getHeight(TreeNode root){
if(root==null) return 0;
return Math.max(getHeight(root.left),getHeight(root.right))+1;
}
}
解法二:(也是递归解法,但是getHeight()优化成checkHeight( ),时间复杂度 O(N),空间复杂度O(H) H为树的高度
import java.util.*;
/*
public 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) {
if(root==null) return true;
if(checkHeight(root)==-1)return false;
else return true;
}
private int checkHeight(TreeNode root){
if(root==null) return 0;
int leftHeight=checkHeight(root.left);
if(leftHeight==-1) return -1;
int rightHeight=checkHeight(root.right);
if(rightHeight==-1) return -1;
if(Math.abs(leftHeight-rightHeight)>1){
return -1;
}else{
return Math.max(leftHeight,rightHeight)+1;
}
}
}