题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个二叉树,判断这是不是平衡二叉树(任意节点左右子节点高度差不超过 1)

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
ans = True
def checkHeight(root:Optional[TreeNode]) -> int:
if not root:
return 0
left = checkHeight(root.left)
right = checkHeight(root.right)
if abs(left - right) > 1:
nonlocal ans
ans = False
return max(left,right) + 1
checkHeight(root)
return ans