题目:给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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 。
# 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 root is None:
return True
if abs(self.maxdepth(root.left)-self.maxdepth(root.right))>1:
print(abs(self.maxdepth(root.left)-self.maxdepth(root.right)))
return False
else:
return True
def maxdepth(self,root):
if root is None:
return 0
return max(self.maxdepth(root.left),self.maxdepth(root.right))+1
测试不通过,这样无法判断每个节点的左右子树是否相差1,只能判断第二层的节点。对于以下测试用例,无法通过:
[1,2,2,3,null,null,3,4,null,null,4]
所以需要遍历每个节点,采用递归的方式:
# 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 root is None:
return True
if abs(self.maxdepth(root.left)-self.maxdepth(root.right))>1:
print(abs(self.maxdepth(root.left)-self.maxdepth(root.right)))
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def maxdepth(self,root):
if root is None:
return 0
return max(self.maxdepth(root.left),self.maxdepth(root.right))+1
取左右节点判断结果的与,有一个为假即为假