採用自底向上,複雜度爲O(n)
getDepth這個方法返回一個數,要麼是-1,要麼是這個平衡二叉樹的深度,最後只要判斷不是-1就是平衡二叉樹
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getDepth(root) != -1;
}
private int getDepth(TreeNode root){
if(root == null)
return 0;
int left = getDepth(root.left);
if(left == -1)
return -1;
int right = getDepth(root.right);
if(right == -1)
return -1;
return Math.abs(left-right) > 1?-1:Math.max(left,right)+1;
}
}