Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Envoy
- 리스트의 리스트
- Dynamic Programmin
- 동적 프로그래밍
- 프로그래머스
- 규칙없음
- minimum path sum
- No Rules Rules
- 알고리즘
- 파이썬
- technical debt
- mysql #numa #swap #memory
- 리트코드
- 나는 아마존에서 미래를 다녔다
- BFS
- LongestPalindromicSubstring
- 기술적 채무
- leetcode
- 트리
- 블린이
- 독후감
- 삼성인 아마조니언 되다
- 그거봤어?
- Python
- 아마조니언
- 김태강
- 삼성역량테스트
- 와썹맨
- Unique Paths
- list of list
Archives
- Today
- Total
개발자가 되고 싶은 준개발자
[LeetCode] 102. Binary Tree Level Order Traversal 풀이 및 코드 본문
문제
트리를 level 순으로 순회하여 각 레벨 별 노드의 값을 리턴한다.
풀이
이 문제는 트리를 level 순으로 순회하는 문제이기 때문에 BFS(너비 우선 탐색)가 적합하다.
트리의 루트부터 leaf까지 순회를 하면서 한 레벨 씩 리스트에 담는다. 한 레벨 씩 리스트에 담기 위해서는 이전 레벨의 노드들의 리스트를 받아 해당 노들들의 left, right을 리스트에 넣으면 된다.
코드
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return root
binary_tree_list, queue = [], [root]
while len(queue) != 0:
children, parent_val = [], []
while len(queue) != 0:
parent = queue.pop(0)
parent_val.append(parent.val)
if parent.left:
children.append(parent.left)
if parent.right:
children.append(parent.right)
queue = children
binary_tree_list.append(parent_val)
return binary_tree_list
리트코드 제출 결과
참조
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 100. Same Tree 풀이 및 코드 (1) | 2020.09.26 |
---|---|
[LeetCode] 103. Binary Tree Zigzag Level Order Traversal 풀이 및 코드 (1) | 2020.09.26 |
[LeetCode] 101. Symmetric Tree 풀이 및 코드 (1) | 2020.09.26 |
[LeetCode] 91. Decode Ways 풀이 및 코드 (0) | 2020.09.20 |
[LeetCode] 64. Minimum Path Sum 풀이 및 코드 (0) | 2020.09.19 |