赞
踩
1. 637:二叉树的层平均值
- # 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
2. 429:N叉树的层序遍历
- """
- # 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
- # 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
4. 104:二叉树的最大深度
- # 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)
5. 226:翻转二叉树
- # 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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。