Skip to content

Commit bc41bcb

Browse files
committed
feat: balanced-binary-tree
1 parent 5eb6ff4 commit bc41bcb

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: bt.balanced-binary-tree.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
class Solution:
9+
"""
10+
110. 平衡二叉树
11+
https://leetcode-cn.com/problems/balanced-binary-tree/
12+
给定一个二叉树,判断它是否是高度平衡的二叉树。
13+
本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
14+
"""
15+
def isBalanced(self, root: TreeNode) -> bool:
16+
if not root:
17+
return True
18+
19+
if not self.isBalanced(root.left) or not self.isBalanced(root.right):
20+
return False
21+
22+
left = self.maxDepth(root.left) + 1
23+
right = self.maxDepth(root.right) + 1
24+
return abs(left - right) <= 1
25+
26+
# 查询节点的最大深度
27+
def maxDepth(self, root):
28+
if not root:
29+
return 0
30+
31+
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

0 commit comments

Comments
 (0)