- 637:二叉树的层平均值
python
复制代码
# 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 averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
def dfs(node, level, res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
dfs(node.left, level + 1, res)
dfs(node.right, level + 1, res)
res = []
level = 0
dfs(root, level, res)
final_res = []
for i in res:
final_res.append(sum(i) / len(i))
return final_res
- 429:N叉树的层序遍历
python
复制代码
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
def dfs(node, level, res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
for child in node.children:
dfs(child, level + 1, res)
res = []
level = 0
dfs(root, level, res)
return res
- 515:在每个树行中找最大值
python
复制代码
# 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 largestValues(self, root: Optional[TreeNode]) -> List[int]:
def dfs(node, level, res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
dfs(node.left, level + 1, res)
dfs(node.right, level + 1, res)
res = []
level = 0
dfs(root, level, res)
final_res = []
for i in res:
final_res.append(max(i))
return final_res
- 104:二叉树的最大深度
python
复制代码
# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
def dfs(node, level, res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
dfs(node.left, level + 1, res)
dfs(node.right, level + 1, res)
res = []
level = 0
dfs(root, level, res)
return len(res)
- 226:翻转二叉树
python
复制代码
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node):
if not node:
return
node.left, node.right = node.right, node.left
dfs(node.left)
dfs(node.right)
dfs(root)
return root