简繁EN

LeetCodeNo. 029

【LeetCode with Python】 110. Balanced Binary Tree

目錄

題目

原題頁面:https://leetcode.com/problems/balanced-binary-tree/
題目型別:Tree, Depth-first Search
難度評價:Easy
類似題目:(E) Maximum Depth of Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


分析

判斷一棵樹是否高度平衡,即每個節點的左右子樹高度相差不過1,參考BBT二叉平衡樹或AVL的定義。還是用常見的二叉樹遞歸回溯解法。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def checkBBT(self, root):
if None == root:
return True, 0
isLeftBBT, leftDepth = self.checkBBT(root.left)
isRightBBT, rightDepth = self.checkBBT(root.right)
isBBT = isLeftBBT and isRightBBT and abs(leftDepth - rightDepth) <= 1
depth = max(leftDepth, rightDepth) + 1
return isBBT, depth

# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return self.checkBBT(root)[0]

本文地址:https://xnerv.wang/zh-tw/leetcode-balanced-binary-tree/