Description:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
Return false.
Solution:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root == None:
return True
self.balanced = True
def height(node):
if node == None:
return 0
hl = height(node.left)
hr = height(node.right)
if abs(hl-hr) > 1:
self.balanced = False
return max(hl,hr)+1
height(root)
return self.balanced
Runtime: 64 ms, faster than 46.61% of Python3 online submissions for Balanced Binary Tree.
Memory Usage: 19.4 MB, less than 5.27% of Python3 online submissions for Balanced Binary Tree.
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(node):
if node == None:
return 0
hl = height(node.left)
hr = height(node.right)
if abs(hl-hr) > 1 or hl == -1 or hr == -1:
return -1
return max(hl,hr) + 1
return height(root) != -1
Runtime: 56 ms, faster than 83.59% of Python3 online submissions for Balanced Binary Tree.
Memory Usage: 19.6 MB, less than 5.27% of Python3 online submissions for Balanced Binary Tree.
Wrong answer:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root == None:
return True
stack = [root]
cache = []
i = 0
flag = 0
while stack:
print([n.val for n in stack if n != None])
for n in stack:
if n.left != None:
cache.append(n.left)
if n.right != None:
cache.append(n.right)
stack = cache
cache =[]
if len(stack) < pow(2,i):
flag += 1
if flag > 1:
break
i += 1
return flag < 2
Wrong answer: 一行行扫描,最终对比最下面一行的高度值。空间随着深度的增加,指数增加,TLE
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root == None:
return True
def duplicate(ls):
cache = []
for l in ls:
cache.append(l)
cache.append(l)
return cache
def judge(ls):
while len(ls) >= 2:
for i in range(0,len(ls),2):
if abs(ls[i] - ls[i+1]) > 1:
return False
ls[i] = max(ls[i],ls[i+1])
ls = ls[::2]
return True
stack = [root]
cache = []
height = [0]
flag = True
while flag:
height = duplicate(height)
flag = False
for i,n in enumerate(stack):
if n != None:
if n.left != None:
cache.append(n.left)
height[i*2] += 1
flag = True
else:
cache.append(None)
if n.right != None:
cache.append(n.right)
height[i*2+1] += 1
flag = True
else:
cache.append(None)
else:
cache.append(None)
cache.append(None)
stack = cache
cache =[]
return judge(height)