当前位置: 首页 > 后端技术 > Python

力扣-采访问题04.04,Checkbalance【Python】

时间:2023-03-26 01:59:14 Python

问题LeetCode实现了一个函数来检查二叉树是否平衡。在这个问题中,一棵平衡树的定义如下:在任意一个节点,它的两个子树的高度差不超过1。例1:给定一棵二叉树[3,9,20,null,null,15,7]3/\920/\157返回true。示例2:给定一棵二叉树[1,2,2,3,3,null,null,4,4]1/\22/\33/\44返回false。递归的思想不仅是当根节点左右高度差小于等于1时,左右子树也必须满足平衡码Python3#二叉树节点的定义#classTreeNode:#def__init__(self,x):#self.val=x#self.left=None#self.right=Noneclass解决方案:defisBalanced(self,root:TreeNode)->bool:ifnotroot:returnTrue#计算树的高度defheight(root):ifnotroot:return0returnmax(height(root.left),height(root.right))+1#不仅根节点的左右高度差小于等于1,左右子树也必须满足balancereturnabs(height(root.left)-height(root.right))<=1andself.isBalanced(root.left)andself.isBalanced(root.right)链接GitHub