方法一:
依次判断每个结点的左右子树高度,使用一个获取二叉树深度的递归函数:
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null){
return true;
}
int count = Math.abs(TreeDepth(root.left) - TreeDepth(root.right));
return count <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int TreeDepth(TreeNode root) {
int left = 0, right = 0;
if (root == null){
return 0;
}else {
left = TreeDepth(root.left);
right = TreeDepth(root.right);
return Math.max(left,right) + 1;
}
}
}
存在的问题:先序遍历会对结点进行重复访问
方法二:
使用后序遍历,从下往上遍历,如果子树是平衡的则返回子树高度,如果子树不平衡,那么直接返回-1(代表不平衡)
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return TreeDepth(root) != -1;
}
public int TreeDepth(TreeNode root) {
int left = 0, right = 0;
if (root == null){
return 0;
}else {
left = TreeDepth(root.left);
if (left == -1){
return -1;
}
right = TreeDepth(root.right);
if (right == -1){
return -1;
}
return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left,right);
}
}
}