110.平衡二叉树
解法:递归(后序)
# 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 dfs(root):
if not root:
return 0
left = dfs(root.left)
right = dfs(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
else:
return 1 + max(left, right)
return dfs(root) >= 0
257. 二叉树的所有路径
解法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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path = []
res = []
queue = [root]
path.append(str(root.val))
while path:
node = queue.pop(0)
rout = path.pop(0)
if not node.left and not node.right:
res.append(rout)
if node.left:
queue.append(node.left)
path.append(rout + '->' + str(node.left.val))
if node.right:
queue.append(node.right)
path.append(rout + '->' + str(node.right.val))
return res
解法2:递归(前序)(回溯)
# 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]:
# method 2
def findpath(root,path,res):
path += str(root.val)
if not root.left and not root.right:
res.append(path)
if root.left:
findpath(root.left,path + '->',res)
if root.right:
findpath(root.right,path + '->',res)
path = ''
res = []
findpath(root,path,res)
return res
404.左叶子之和
解法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 sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
# method 1
if not root:
return 0
total = 0
queue = [root]
while queue:
node = queue.pop()
if node.left:
if not node.left.left and not node.left.right:
total += node.left.val
queue.append(node.left)
if node.right:
queue.append(node.right)
return total
解法2:递归(后序)
# 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:
# method 2
if not root:
return 0
left = self.sumOfLeftLeaves(root.left)
right = self.sumOfLeftLeaves(root.right)
total = 0
if root.left:
if not root.left.left and not root.left.right:
total = root.left.val
return total + left + right