Scribbling

LeetCode: 103. Binary Tree Zigzag Level Order Traversal 본문

Computer Science/Coding Test

LeetCode: 103. Binary Tree Zigzag Level Order Traversal

focalpoint 2021. 10. 20. 16:21

102번 문제를 풀면 하나 더 주는 공짜 문제.

밑의 코드만 추가해준다.

        for i in range(len(ret)):
            if i % 2 == 1:
                ret[i].reverse()

https://focalpoint.tistory.com/128

 

LeetCode: 102. Binary Tree Level Order Traversal - 시바견의 끄적임

BFS하면서 기록해준다. from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # s..

focalpoint.tistory.com

from collections import deque
# 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 zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        ret = []
        q = deque()
        q.append((root, 0))
        while q:
            cur_node, cur_level = q.popleft()
            if len(ret) == cur_level:
                ret.append([cur_node.val])
            else:
                ret[cur_level].append(cur_node.val)
            if cur_node.left != None:
                q.append((cur_node.left, cur_level+1))
            if cur_node.right != None:
                q.append((cur_node.right, cur_level+1))
        for i in range(len(ret)):
            if i % 2 == 1:
                ret[i].reverse()
        return ret