题目
代码
执行用时:56 ms, 在所有 Python3 提交中击败了54.86% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了35.23% 的用户
通过测试用例:227 / 227
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
if not root:
return True
return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
【方法2】
执行用时:60 ms, 在所有 Python3 提交中击败了42.01% 的用户
内存消耗:19.8 MB, 在所有 Python3 提交中击败了19.63% 的用户
通过测试用例:227 / 227
class Solution:
def dep(self,root):
if not root:
return 0
return max(self.dep(root.left),self.dep(root.right))+1
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return abs(self.dep(root.left)-self.dep(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
【方法3】
执行用时:64 ms, 在所有 Python3 提交中击败了31.43% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了53.92% 的用户
通过测试用例:227 / 227
class Solution:
def dep(self,root):
if not root:
return 0
return max(self.dep(root.left),self.dep(root.right))+1
def isBalanced(self, root: TreeNode) -> bool:
queue=[root]
if not root:return True
while queue:
root=queue.pop()
if abs(self.dep(root.left)-self.dep(root.right))>1:
return False
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return True
【方法4】
执行用时:36 ms, 在所有 Python3 提交中击败了99.53% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了48.05% 的用户
通过测试用例:227 / 227
class Solution:
def depth(self,root):
if not root:
return 0
L=self.depth(root.left)
R=self.depth(root.right)
if L==-1 or R==-1 or abs(L-R)>1:
return -1
return max(L,R)+1
def isBalanced(self, root: TreeNode) -> bool:
return self.isBalanced(root)>=0