[LeetCode][Python3] 102. Binary Tree Level Order Traversal
2019. 1. 22. 01:11 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/binary-tree-level-order-traversal/
My Solution :
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret, queue = [], [root]
while root and queue:
node_val, node_queue = [], []
for node in queue:
node_val.append(node.val)
if node.left:
node_queue.append(node.left)
if node.right:
node_queue.append(node.right)
ret.append(node_val)
queue = node_queue
return ret
Comment :
위 풀이는 다른 풀이를 참고한 것이고, 아래 풀이는 내가 처음 문제를 접했을 때 시도한 풀이이다.
My Solution2 :
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
dic = {}
queue = deque([(root, 0)])
while root and queue:
node, level = queue.popleft()
dic.setdefault(level, []).append(node.val)
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
ret = [dic[level] for level in sorted(dic)]
return ret
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 162. Find Peak Element (0) | 2019.01.25 |
---|---|
[LeetCode][Python3] 328. Odd Even Linked List (0) | 2019.01.25 |
[LeetCode][Python3] 287. Find the Duplicate Number (0) | 2019.01.25 |
[LeetCode][Python3] 75. Sort Colors (0) | 2019.01.24 |
[LeetCode][Python3] 230. Kth Smallest Element in a BST (0) | 2019.01.15 |
[LeetCode][Python3] 454. 4Sum II (1) | 2019.01.13 |
[LeetCode][Python3] 78. Subsets (0) | 2019.01.13 |
[LeetCode][Python3] 238. Product of Array Except Self (0) | 2019.01.12 |
최근에 달린 댓글 최근에 달린 댓글