반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 637 | Average of Levels in Binary Tree | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/average-of-levels-in-binary-tree/
문제
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within $10^{-5}$ of the actual answer will be accepted.
조건
- The number of nodes in the tree is in the range [1, $10^4$].
- $-2^{31}$ <= Node.val <= $2^{31}$ - 1
내 풀이
Tree구조는 recursive한 함수를 짜는 것이 좋다.
recursive하게 훑으며 values라는 리스트에 각 depth별 값을 모은다.
나중에 depth별로 평균을 구한 후 이를 리턴하면 된다.
코드
# 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]:
values = []
def search(root, depth):
nonlocal values
if not root:
return
if len(values) < depth+1:
values.append([])
values[depth].append(root.val)
search(root.left, depth+1)
search(root.right, depth+1)
search(root, 0)
ans = [sum(x)/len(x) for x in values]
return ans
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 814 | Binary Tree Pruning | Python (0) | 2022.09.06 |
---|---|
[LeetCode] 429 | N-ary Tree Level Order Traversal | Python (0) | 2022.09.05 |
[LeetCode] 1448 | Count Good Nodes in Binary Tree | Python (0) | 2022.09.01 |
[LeetCode] 417 | Pacific Atlantic Water Flow | Python (0) | 2022.08.31 |
[LeetCode] 48 | Rotate Image | Python (0) | 2022.08.30 |
Comments