题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
class Solution:
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
# write code here
if pRoot is None:
return True
h_left = self.get_height(pRoot.left)
h_right = self.get_height(pRoot.right)
if (abs(h_left-h_right)<=1): #得保证所有左右子树都是平衡二叉树
return self.IsBalanced_Solution(pRoot.right) and self.IsBalanced_Solution(pRoot.left)
return False
def get_height(self, pRoot: TreeNode) -> int:# 计算树的深度
if pRoot is None:
return 0
if pRoot.left is None and pRoot.right is None:
return 1
return max(self.get_height(pRoot.left), self.get_height(pRoot.right))+1
这道题考察“平衡二叉树”和“树的深度的计算”。