题目
代码
执行用时: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

本文探讨四种不同的方法解决二叉树平衡问题,包括深度优先遍历、依赖递归深度计算、广度优先遍历及深度检查。方法4以最短用时和内存消耗通过全部测试,展示了高效解决平衡判断的技巧。
348

被折叠的 条评论
为什么被折叠?



