題目地址:Balanced Binary Tree
題目簡介:
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義爲:一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1。
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
題目解析:
1、遍歷:
二叉樹的深度問題,簡單問題。每到一個點判斷一下該點是否滿足條件。
C++:
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == NULL)
return true;
if (abs(helper(root -> left) - helper(root -> right)) > 1)
return false;
return isBalanced(root -> right) && isBalanced(root -> left);
}
int helper(TreeNode* root) {
if (root == NULL)
return 0;
return 1 + max(helper(root -> left), helper(root -> right));
}
};
Python:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root == None:
return True
if abs(self.helper(root.left) - self.helper(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def helper(self, root):
if root == None:
return 0
return 1 + max(self.helper(root.left), self.helper(root.right))
2、提前終止
上面的簡單法對於越低層的點遍歷的次數越多,對於第n層的點遍歷了n次。考慮到二叉樹的存儲結構,其時間效率爲O(nlogn)。但是浪費了不必要的時間,只要從下往上看,出現了不符合條件的分支便終止結束即可。
終止的條件是什麼呢?根據題目,只要出現左右兩端的點不符合層數差別爲1,那麼便返回錯誤結果。假設最下面一層的編號爲0,每往上走一層加1,那麼每層的深度將大於等於0。將不符合條件的節點的深度賦值爲-1,就能表示出有錯誤。
Python:
class Solution(object):
def isBalanced(self, root):
height = self.get_height(root)
return height != -1
def get_height(self, root):
if not root:
return 0
left = self.get_height(root.left)
right = self.get_height(root.right)
if left == -1 or right == -1 :
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1