题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
题目:https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
递归遍历二叉树的每一个节点,求出节点左右子树的高度,如果高度之差不超过1,则为平衡二叉树。先求高度(递归求),再判断是不是平衡二叉树(递归判断)。
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
class Solution:
def TreeDepth(self , pRoot: TreeNode) -> int:
if pRoot==None:
return 0
else:
return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
# 递归遍历二叉树的每一个节点,求出节点左右子树的高度,如果高度之差不超过1,则为平衡二叉树
if not pRoot:
return True #空树是平衡二叉树
#递归求左右子树高度,所以要写递归求高度的函数
ldepth=self.TreeDepth(pRoot.left)
rdepth=self.TreeDepth(pRoot.right)
diff=ldepth-rdepth
if abs(diff)>1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
查看16道真题和解析
