
给定一个二叉树,判断它是否是 平衡二叉树
二叉搜索树(BST)
-
性质:左子树所有节点值 < 根节点值 < 右子树所有节点值
-
目的:快速查找(O(log n) 在平衡情况下)
-
不保证平衡
平衡二叉树
-
性质:每个节点左右子树高度差不超过1
-
目的:避免树退化成链表,保持操作效率
-
不保证有序性
python
# 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:
self.res = True
def helper(root):
if not root:
return 0
left = helper(root.left) + 1
right = helper(root.right) + 1
#print(right, left)
if abs(right - left) > 1:
self.res = False
return max(left, right)
helper(root)
return self.res
python
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
if not root:
return True
return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)