- 第一想法:
用maxDepth and minDepth,差值大于1,就不是平衡的。
- 看完代码随想录的想法:
深度和高度是不一样的。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def getHeight(root): #后续遍历
if not root:
return 0
leftHeight = getHeight(root.left)
if leftHeight == -1:
return -1
rightHeight = getHeight(root.right)
if rightHeight == -1:
return -1
if abs(rightHeight-leftHeight) > 1:
return -1
else:
return 1+max(leftHeight,rightHeight)
if getHeight(root) == -1:
return False
else:
return True
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result = []
path = ''
if not root:
return []
def dfs(cur, path, result):
path += str(cur.val)
if not cur.left and not cur.right:
result.append(path)
if cur.left:
dfs(cur.left, path+'->', result)
if cur.right:
dfs(cur.right, path+'->', result)
dfs(root,path,result)
return result
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_sum = self.sumOfLeftLeaves(root.left)
right_sum = self.sumOfLeftLeaves(root.right)
cur_l = 0
if root.left and not root.left.left and not root.left.right:
cur_l = root.left.val
return left_sum + right_sum + cur_l
这几题都属于看代码很好理解,但是自己写没写出来的。