본문 바로가기

Algorithm/LeetCode

[LeetCode][Python3] 116. Populating Next Right Pointers in Each Node

반응형
"""
# 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.

 

 

반응형