输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
返回 false 。
限制:
- 0 <= 树的结点个数 <= 10000
Python 解答:
1.笨方法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def depth(root):
if not root:
return 0
else:
left = depth(root.left)
right = depth(root.right)
return 1+max(left, right)
flag = True
def isHelper(root):
if not root:
return True
else:
isHelper(root.left)
isHelper(root.right)
if abs(depth(root.left)-depth(root.right)) > 1:
nonlocal flag
flag = False
isHelper(root)
return flag
2.求深度和判断合并
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
flag = True
def depth(root):
if not root:
return 0
else:
left = depth(root.left)
right = depth(root.right)
if abs(left-right) > 1:
nonlocal flag
flag = False
return 1+max(left, right)
depth(root)
return flag
留言