题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/creation/write/md?entryPahttps://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=295&tqId=23250&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fojge=https%3A%2F%2Fwww.nowcoder.com%2Fpractice%2F8b3b95850edb4115918ecebdf1b4d222%3FtpId%3D295%26tqId%3D23250%26ru%3D%2Fexam%2Foj%26qru%3D%2Fta%2Fformat-top101%2Fquestion-ranking%26sourceUrl%3D%252Fexam%252Foj&type=0&qurl=%2Fpractice%2F8b3b95850edb4115918ecebdf1b4d222
# 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 #如果节点为空,那么说明该节点不存在默认为True不需要进行比较 if not pRoot: return True #要比较左右字树的深度,那么必须有办法获取到左右字数的深度,获取深度的函数用GetDepth函数 #获取深度的函数的逻辑就是当根节点不为空时,深度为左子树的深度对比右边字数的深度哪个大取哪个,然后+1,当遍历到最后,为空时返回0,叶子节点就是空加1深度为1 def GetDepth(root): if root: return max(GetDepth(root.left),GetDepth(root.right))+1 else: return 0 #print(GetDepth(pRoot)) if abs(GetDepth(pRoot.left)-GetDepth(pRoot.right))>1: return False else: return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)