# class TreeNode:
# def __init__(self, x):, right_shift
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
class Solution:
#方法1:自顶向下,递归
def Deep(self,Root:TreeNode):
#求深度
if Root == None:
return 0
left = self.Deep(Root.left)
right = self.Deep(Root.right)
return left+1 if left>right else right+1
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
# write code here
#递归
#空树为平衡二叉树
if not pRoot:
return True
left = self.Deep(pRoot.left)
right = self.Deep(pRoot.right)
if left-right>1 or right-left>1:
return False
#左右子树也得是平衡树
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
#方法2:自底向上
def getdepth(self,root:TreeNode)->int:
if root==None:#空节点深度为0
return 0
left = self.getdepth(root.left)
if left == -1:
return -1
right = self.getdepth(root.right)
if right == -1:
return -1
return -1 if abs(left-right)>1 else max(left,right)+1
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
if pRoot==None:
return True
return self.getdepth(pRoot)!=-1
NC62 判断是不是平衡二叉树
最新推荐文章于 2024-11-17 18:49:52 发布