題目難度: 簡單
原題連結[1]
今天繼續更新劍指 offer 系列, 老樣子晚上 6 點 45 分準時更新公眾號 每日精選算法題, 大家記得關注哦~ 另外在公眾號裡回復 offer 就能看到劍指 offer 系列當前連載的所有文章了
輸入一棵二叉樹的根節點,判斷該樹是不是平衡二叉樹。如果某二叉樹中任意節點的左右子樹的深度相差不超過 1,那麼它就是一棵平衡二叉樹。
給定二叉樹 [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7返回 true 。
給定二叉樹 [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4返回 false 。
class Solution: def isBalanced(self, root: TreeNode) -> bool: 遞歸出口: 如果節點為空或者不平衡, 返回0, 無需繼續遞歸了 return 0 ldepth = getDepth(node.left) rdepth = getDepth(node.right) if abs(ldepth - rdepth) > 1: 返回當前節點自身的深度 return max(ldepth, rdepth) + 1 getDepth(root) return balance
[1]
原題連結: https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/