반응형
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root: return root
queue = []
queue.append(root)
while(len(queue)!=0):
leftqueue = []
prenode = queue.pop(0)
if prenode.left != None: leftqueue.append(prenode.left)
if prenode.right!= None: leftqueue.append(prenode.right)
while(len(queue)!=0):
node = queue.pop(0)
if node.left!=None: leftqueue.append(node.left)
if node.right!=None: leftqueue.append(node.right)
prenode.next = node
prenode = node
queue.extend(leftqueue)
return root
코드의 핵심은 마지막의 next를 어떻게 None으로 처리할꺼냐 였다.
그래서 while문을 사용하여 처리를 하였다.
Runtime: 60 ms, faster than 75.99% of Python3 online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 15.8 MB, less than 5.97% of Python3 online submissions for Populating Next Right Pointers in Each Node.
반응형
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 130. Surrounded Regions (0) | 2021.01.01 |
---|---|
[LeetCode][Python3] 111. Minimum Depth of Binary Tree (0) | 2020.12.31 |
[LeetCode][Python3] 107. Binary Tree Level Order Traversal II (0) | 2020.12.31 |
[LeetCode][Python3] 103. Binary Tree Zigzag Level Order Traversal (0) | 2020.12.31 |
[LeetCode][Python3] 104. Maximum Depth of Binary Tree (0) | 2020.12.28 |