平衡二叉樹-II
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹(它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1)。
在這裏,我們只需要考慮其平衡性,不需要考慮其是不是排序二叉樹
方法1:自頂向下
思路分析:
從根節點出發開始遞歸,依次判斷左右子樹的深度差是否<1,同時還要判斷當前的左右子樹是否平衡;
遞歸條件:左右子樹深度差<1且左右子樹均爲平衡樹;
終止條件:上述的非命題
複雜度
時間複雜度:O(NlogN) 每層節點的求深度操作O(N)*樹的深度遍歷O(logN)
空間複雜度:O(N)
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
return Math.abs(Depth(root.left) - Depth(root.right)) <= 1
&& IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private int Depth(TreeNode root){
if(root == null) return 0;
return Math.max(Depth(root.left),Depth(root.right)) + 1;
}
}
方法2: 自底向上
對二叉樹做後序遍歷,從底至頂返回子樹深度,若判定某子樹不是平衡樹則 “剪枝” ,直接向上返回。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null) return true;
if(depth(root) == -1) return false;
else return true;
}
private int depth(TreeNode root){
if(root == null) return 0;
int left = depth(root.left);
if(left == -1) return -1;
int right = depth(root.right);
if(right == -1) return -1;
if(Math.abs(left - right) <= 1){
return Math.max(left, right) + 1;
}else{
return -1;
}
}
}