110.平衡二叉树
– 最大深度的思路 考虑一下返回条件
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def getDepth(node):
if not node:
return 0
left = getDepth(node.left)
if left == -1:
return -1
right = getDepth(node.right)
if right == -1:
return -1
if abs(left-right)>1:
return -1
return 1 + max(left,right)
return False if getDepth(root)==-1 else True
257. 二叉树的所有路径
–迷迷糊糊写出来了,代码还可以精简
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def getPath(res,path,node):
if not node:
return
if not path:
path = str(node.val)
else:
path += '->' + str(node.val)
if not node.left and not node.right:
res.append(path)
return
getPath(res,path,node.left)
getPath(res,path,node.right)
return
res = []
getPath(res,'',root)
return res
404.左子树之和
–开始写错的地方在,判断为左子树的时候,应该是其左右节点都不存在(写成了左节点不存在就算)
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if root.left and not root.left.left and not root.left.right:
return root.left.val + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
else:
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)