題目描述
實現一個函數,檢查二叉樹是否平衡。在這個問題中,平衡樹的定義如下:任意一個節點,其兩棵子樹的高度差不超過 1。
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/check-balance-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析:
後序遍歷2叉樹,依次判斷左右子樹是否平衡,如果不平衡直接返回False,否則判斷父節點是否平衡。
函數同時返回當前節點的高度和平衡性
代碼實現
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def node_height_and_balance(node):
if node is None:
return 0, True
left_height, left_balance = node_height_and_balance(node.left)
if not left_balance:
return 0, False
right_height, right_balance = node_height_and_balance(node.right)
if not right_balance:
return 0, False
return max(left_height, right_height) + 1, abs(left_height - right_height) < 2
height, is_balance = node_height_and_balance(root)
return is_balance