LeetCode-110、平衡二叉树-简单
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
代码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:
return False if self.depth(root)==-1 else True
def depth(self, node):
if not node:
return 0
left = self.depth(node.left)
if left == -1:
return -1
right = self.depth(node.right)
if right == -1:
return -1
return max(left, right)+1 if abs(left-right)<=1 else -1
代码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:
if not root:
return True
return abs(self.depth(root.left)-self.depth(root.right))<=1 and \
self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, node):
if not node:
return 0
return max(self.depth(node.left), self.depth(node.right))+1
来源:CSDN
作者:clover_my
链接:https://blog.csdn.net/clover_my/article/details/104226789