110 平衡二叉树
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if not root:
return 0
return 1+max(height(root.left),height(root.right))
if not root:
return True
return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if not root:
return 0
l=height(root.left)
r=height(root.right)
if l==-1 or r==-1 or abs(l-r)>1:
return -1
return 1+max(l,r)
return height(root)>=0
257 二叉树的所有路径
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def sub(root,path):
if not root:
return
path+=str(root.val)
if not root.left and not root.right:
paths.append(path)
return
path+="->"
sub(root.left,path)
sub(root.right,path)
paths=[]
sub(root,'')
return paths
404 左叶子之和
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
isLeafNode=lambda node: not node.left and not node.right
def dfs(root):
if not root:
return 0
ans=0
if root.left:
ans+=root.left.val if isLeafNode(root.left) else dfs(root.left)
if root.right and not isLeafNode(root.right):
ans+=dfs(root.right)
return ans
if not root:
return 0
return dfs(root)